python - scrapy - 无法正确地将多个 URL 从 <p> 标签提取到项目列表中

标签 python xpath dictionary css-selectors scrapy

我几乎是 Scrapy 和 Python 的新手,所以如果这个问题听起来很愚蠢,请耐心等待。我试图抓取的内容全部位于网站上的一个或多个段落标签内。如果字段(URL)位于多个段落标签中,我将很难提取它们。如果每个 block 的每个段落标记只有一个链接,或者在表格单元格中,我可以轻松获取它们。但在这种情况下,即使花了一天多的时间,我也无法从多个段落标签中提取这些多个链接。

我尝试提取的内容具有以下 HTML 源结构:

<p class="date">June 30, 2014 </p>
<h2> SOME TITLE 1 </h2>
<p> SOME TEXT 1 <a href="http://www.link1.com">LINK 1</a> and the <a href="http://www.link2.com">LINK 2</a>.</p>

<p class="date">June 27, 2014</p>
<h2>SOME TITLE 2</h2>
<p>SOME TEXT 2-A </p>
<p>SOME TEXT 2-B <a href="meetings.php">here</a>. SOME TEXT </p>
<p>SOME TEXT 2-C <a href="website.php">WCI, Inc. website</a>, SOME TEXT. </p>

<p class="date">June 27, 2014 </p>
<h2>SOME TITLE 3 </h2>
<p>SOME TEXT 3 <a href="http://www.anotherlink.com">SOME TEXT</a>.</p>

<p><a href="news-archive.php" class="button buttonLtGray floatR">Previous Entries</a></p>

请帮忙。我的代码如下:

class Wcispider(Spider):

name = "wci"
allowed_domains = "www.wci-inc.org/"
start_urls = ["http://www.wci-inc.org/index.php"]

def parse(self, response):

    items = []
    sel = Selector(response)

    date = sel.css(".date::text")

    i = 0

    for eacDate in date:
        item = WciItem()

        item['date'] = eacDate.extract()

        item['title'] = sel.xpath('//*[@id="news"]/h2').extract()[i]
        item['url'] = sel.css(".date ~ p a").extract()[i]

        print item['date']
        print item['title']
        print item['url']
        i += 1
        items.append(item)

    return items

最佳答案

由于每个“新闻帖子正文”中可以有多个链接,因此一次一个迭代将不起作用。

我会尝试将它们分组到“新闻发布日期”节点下,然后循环一段时间。 (不幸的是,您的目标文档没有包含新闻帖子:)

Scrapy 选择器的一个很酷的事情是,您可以在 xpath 调用的结果上调用 xpath。检查一下:

#get all interesting date paragraphs
date = sel.xpath('//*/p[@class="date"]')

for eacDate in date:
    #eacDate is a paragraph node
    #extract all of the paragraphs after this one at the same level in the DOM,
    #then loop until you find a date paragraph, since that marks the start of the next section
    urls = []
    next_paragraphs = eacDate.xpath("following-sibling::p")
    for p in next_paragraphs:
        if p.xpath("@class").extract() == [u'date']:
            break
        urls.extend(p.xpath("a/@href").extract())
    print urls

您可能想阅读 XPath 轴:http://www.w3schools.com/xpath/xpath_axes.asp

关于python - scrapy - 无法正确地将多个 URL 从 <p> 标签提取到项目列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25251810/

相关文章:

python - 任何 Python ORM(SQLAlchemy?)都可以与 Google App Engine 一起使用吗?

python - 如何将数组写入文件,然后调用该文件并将更多内容添加到数组中?

如果存在匹配,Python 将 dict 中的值附加到具有两个值的现有 dict 中

android - 错误二进制 XML 文件行 #7 : Error inflating class com. esri.android.map.MapView

python - celery 设计帮助 : how to prevent concurrently executing tasks

python - 如何使用正则表达式删除python字符串中的特定模式?

python - 带有部分字符串的 xpath 搜索属性

xml - Schematron-基于其位置的元素验证

xpath - 一行 nokogiri xpath 查找

c++ - 如何执行键类型和映射的通用打印