Python:我可以将Chrome的"Inspect Element" XPath创建工具用作Scrapy spider XPath吗?



我的蜘蛛类如下:

class MySpider(BaseSpider):
    name =  "dropzone"
    allowed_domains = ["dropzone.com"]      
    start_urls = ["http://www.dropzone.com/cgi-bin/forum/gforum.cgi?post=4724043"]
    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        reply = response.xpath('//*[@id="wrapper"]/div/div/table/tbody/tr/td/div/div/center/table/tbody/tr/td/table/tbody/tr/td/font/table/tbody/tr/td/table/tbody/tr/td/font/b')
        dates = response.xpath('//*[@id="wrapper"]/div/div/table/tbody/tr/td/div/div/center/table/tbody/tr/td/table/tbody/tr/td/font/table/tbody/tr/td/font/small')
        items = []
        for posts, day in zip(reply, dates):
            item = DozenItem()
            item["Reply"] = posts.re('/text()')
            item["Date"] = day.re('/text()')
            items.append(item)
        return items

我在源代码中专门选择了该项目,然后右键单击,选择"复制XPath",然后将其粘贴到我的xpath中。

但。。。。。当然,这是行不通的。我的外壳没有说它爬行或刮擦了任何东西,我的 CSV 是空的。

最初像往常一样创建了自己的XPath,但它也不起作用,Chrome选项引起了我的兴趣。通常,我只在我的 XPath 中深入包含 3 或 4 个标签。这是否适合下面提供的 html?

该网站是一个论坛网站,我只想有一个自我更新的抓取工具,它可以抓取一个特定的帖子以回复原始帖子,导出日期/帖子。

帖子:

http://www.dropzone.com/cgi-bin/forum/gforum.cgi?post=4724043

我认为帖子日期 HTML 提供了足够的标签:

<br>
<br>
<!-- FORUM MINI PROFILE -->
Registered: Sep 6, 2012<BR>
Posts: 1850<BR><BR>
</small></font>
 Apr&nbsp;26,&nbsp;2015,&nbsp;7:51&nbsp;AM
<br>
    Post #2 of 11
 (195 views)
<br>
<a href="/cgi-bin/forum/gforum.cgi?post=4724045#4724045">Shortcut</a>
<br>
<img src="http://www.dropzone.com/graphics/forum/clear_shim.gif" width="180" height="1">
</font>
</td>

并且帖子本身的主题指定它是带有"Re:"的回复,这将删除原始帖子的抓取:

<td valign="top" width="100%" style="border-left: 1px solid #CCD2DE">
<!-- Adult Content Filter -->
<table border=0 width="100%">
<tr>
<td valign="top" align="left">
<font face="Verdana,Arial,Helvetica" size=2 color="#212126">
<b>
 Re: [pleasedtomeet] Skydiving with tinnitus?
</b>
 [<small><a href="#4724043">In reply to</a></small>]
</font>
</td>

在大多数情况下,您需要稍微调整浏览器返回的 Xpath,基本原因如下:

  1. HTML 可以在页面加载后通过 JavaScript 进行更改。
  2. HTML 可以由浏览器本身更改。
  3. 它们严重依赖节点位置,并包含许多不必要的元素,忽略了更高效和容错的选择路径。

例如,最常见的浏览器功能是浏览器自动添加到HTML中的tbody元素,如下所示:

<table><tr>...</tr></table>

进入这个:

<table><tbody><tr>...</tr></tbody></table>

由于您在浏览器中看到的 HTML 和从服务器获得的原始 HTML 中的这种以及许多其他差异,您应该在蜘蛛中实现 Xpath 元素之前手动验证 scrapy shell Xpath 元素。

您可以在官方文档中找到有关将开发人员工具与 Scrapy 配合使用的更多信息。

最新更新