【问题标题】:XPath cutting off href attributeXPath 截断 href 属性
【发布时间】:2013-09-08 14:22:46
【问题描述】:

我在使用带有 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

【问题讨论】:

  • 你能展示一下蜘蛛的代码吗?
  • 编辑:从评论中删除代码,谢谢
  • 在你的代码中发布!不在评论中。

标签: python-2.7 xpath scrapy


【解决方案1】:

我认为您的 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文档(doc.scrapy.org/en/latest/topics/…)提到 hxs.select().extract 返回一个 unicode 字符串,这可能与它有关吗?
  • @user2758955 无法真正说出问题所在。我试过你的蜘蛛版本,但它实际上并没有抓取任何东西,即titles 是一个空列表。
  • 当您只是在 shell 中测试 Xpath 时,蜘蛛是否重要?我使用了你的 Xpath,甚至试着只看 //@href 不是很重要,只是出于学习目的而好奇
  • 是的,你可以在 scrapy 的 shell 中测试 xpaths。顺便说一句,您的 xpath 不起作用的原因是页面上没有 spanpl 类。
猜你喜欢
  • 1970-01-01
  • 2023-04-03
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
相关资源
最近更新 更多