XPath截断href属性

3

我在使用Scrapy时遇到了一些XPath问题。

我正在查看一个表格中的链接 - 在浏览器中,查看元素时会列出完整的链接。然而,Scrapy shell却截断了链接的末尾。

来自表格的示例链接:

    http://www.ashp.org/DrugShortages/Current/Bulletin.aspx?id=463

检查元素时:

    <a href="/DrugShortages/Current/Bulletin.aspx?id=463">

在 scrapy shell 中提取会移除 463。

有什么想法吗?

这是爬虫的代码。实际上还没有设置它来通过链接进行爬取,我认为首先应该将所有正确的 XPath 语法设置好。

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from ashp.items import AshpItem

    class MySpider(BaseSpider):
    name = "ashp"
    allowed_domains = ["ashp.org"]
    start_urls = ["http://ashp.org/menu/DrugShortages/CurrentShortages"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        titles = hxs.select("//span[@class='pl']")
        for titles in titles:
            title = titles.select("a/text()").extract()
            link = titles.select("a/@href").extract()
            print title, link

1
你能展示一下爬虫的代码吗? - alecxe
请提供需要翻译的内容。 - user2758955
将其发布在您的代码中!而不是在评论中。 - Arup Rakshit
1个回答

2

我认为你的xpath不正确。这里有一个爬虫,可以打印页面上所有Bulletin链接:

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector


class MySpider(BaseSpider):
    name = "ashp"
    allowed_domains = ["ashp.org"]
    start_urls = ["http://ashp.org/menu/DrugShortages/CurrentShortages"]    

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        links = hxs.select("//div[@id='Mid_3Col']/div/table/tr/td/a")
        for link in links:
            title = link.select("text()").extract()[0]
            link = link.select("@href").extract()[0]
            print title, link

输出:

Acetazolamide Injection /DrugShortages/Current/Bulletin.aspx?id=463 
Acetylcysteine Inhalation Solution /DrugShortages/Current/Bulletin.aspx?id=932 
Acyclovir Injection /DrugShortages/Current/Bulletin.aspx?id=467 
Adenosine Injection /DrugShortages/Current/Bulletin.aspx?id=976 
Alcohol Dehydrated Injection (Ethanol) /DrugShortages/Current/Bulletin.aspx?id=778 
Allopurinol Injection /DrugShortages/Current/Bulletin.aspx?id=998
...

这给出了所需的输出,谢谢!我还是有点困惑我遇到的问题。我正在使用scrapy shell测试不同的输出 - 即使在更新了我的爬虫并成功爬取后,scrapy shell中的输出仍然截断了id号码。有任何想法吗?也许与编码有关?我遵循的scrapy文档(http://doc.scrapy.org/en/latest/topics/selectors.html#scrapy.selector.HtmlXPathSelector)提到hxs.select().extract返回一个unicode字符串,那可能跟它有关吗? - user2758955
1
@user2758955 无法确定问题所在。我尝试了你的爬虫版本,但实际上没有爬取任何内容,即tities为空列表。 - alecxe
当你只是在 shell 中测试 Xpath 时,蜘蛛是否重要?我使用了你的 Xpath,甚至尝试只查看 //@href。这并不是非常重要,只是出于学习目的好奇。 - user2758955
1
是的,你可以在Scrapy的shell中测试xpaths。顺便说一下,你的xpath之所以不起作用是因为页面上没有带有“pl”类的“span”。 - alecxe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接