python - 我如何告诉 Scrapy 只抓取 Xpath 中的链接?

标签 python web-scraping scrapy

我是 Scrapy 的新手,我想做的是制作一个爬虫,它只会跟踪给定 start_urls

上 HTML 元素内的链接

举个例子,假设我只是想让一个爬虫通过 start_urls 设置为 https://www.airbnb.com/s?location=New+York%2C+NY&checkin=&checkout=&guests=1 的 AirBnB 房源。

我不想抓取 URL 中的所有链接,我只想抓取 xpath 中的链接 //*[@id="results"]

目前我正在使用下面的代码来抓取所有的链接,我怎样才能让它只抓取//*[@id="results"]

    from scrapy.selector import HtmlXPathSelector
    from tutorial.items import DmozItem
    from scrapy.contrib.spiders import CrawlSpider, Rule
    from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
    from scrapy.selector import HtmlXPathSelector


    class BSpider(CrawlSpider):
            name = "bt"
            #follow = True
            allowed_domains = ["mydomain.com"]
            start_urls = ["http://myurl.com/path"]
            rules =(Rule(SgmlLinkExtractor(allow = ()) ,callback = 'parse_item', follow=True),)


        def parse_item(self, response):
        {parse code}

任何正确方向的提示将不胜感激, 谢谢!

最佳答案

您可以将 restrict_xpaths 关键字参数传递给 SgmlLinkExtractor。来自 the docs :

  • restrict_xpaths(str 或 list)——是一个 XPath(或 XPath 的列表),它定义了响应中应该从中提取链接的区域。如果给定,将仅扫描那些 XPath 选择的文本以查找链接。

关于python - 我如何告诉 Scrapy 只抓取 Xpath 中的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14028258/

相关文章:

python - 在 python 中按定义的间隔按 id/group 移动平均值

python - 在 BeautifulSoup 4 中将标签内容提取为文本(QUOTE_TAGS 等效)

php - 无法从HTML页面获取表格数据

python - 如何绕过 Scrapy 失败的响应(状态代码 416、999,...)

python - 将 url 链接解析为列表

Python argparse 静态参数

python - 在 python 的 while 循环中使用 continue

python - 已排序的集合 : How do i get (extended) slices right?

java - 为什么使用 Jsoup 解析网站时的 HTML 代码与使用浏览器解析网站时不同

python - 在Scrapy中,如果字符串长度很大,extract_first()不会返回完整的文本