gpt4 book ai didi

python - 在 scrapy 中产生项目和回调请求

转载 作者:太空宇宙 更新时间:2023-11-03 11:22:54 26 4
gpt4 key购买 nike

免责声明:我对 Python 和 Scrapy 都很陌生。

我试图让我的蜘蛛从起始 url 收集 url,跟随那些收集到的 url 和两者:

  1. 为特定项目抓取下一页(并最终返回它们)
  2. 从下一页收集更具体的 url 并遵循这些 url。

我希望能够继续这个产生项目和回调请求的过程,但我不太确定该怎么做。目前我的代码只返回 url,没有项目。我显然做错了什么。任何反馈将不胜感激。

class VSSpider(scrapy.Spider):
name = "vs5"
allowed_domains = ["votesmart.org"]
start_urls = [
"https://votesmart.org/officials/WA/L/washington-state-legislative#.V8M4p5MrKRv",
]

def parse(self, response):
sel = Selector(response)
#this gathers links to the individual legislator pages, it works
for href in response.xpath('//h5/a/@href'):
url = response.urljoin(href.extract())
yield scrapy.Request(url, callback=self.parse1)

def parse1(self, response):
sel = Selector(response)
items = []
#these xpaths are on the next page that the spider should follow, when it first visits an individual legislator page
for sel in response.xpath('//*[@id="main"]/section/div/div/div'):
item = LegislatorsItems()
item['current_office'] = sel.xpath('//tr[1]/td/text()').extract()
item['running_for'] = sel.xpath('//tr[2]/td/text()').extract()
items.append(item)
#this is the xpath to the biography of the legislator, which it should follow and scrape next
for href in response.xpath('//*[@id="folder-bio"]/@href'):
url = response.urljoin(href.extract())
yield scrapy.Request(url, callback=self.parse2, meta={'items': items})

def parse2(self, response):
sel = Selector(response)
items = response.meta['items']
#this is an xpath on the biography page
for sel in response.xpath('//*[@id="main"]/section/div[2]/div/div[3]/div/'):
item = LegislatorsItems()
item['tester'] = sel.xpath('//div[2]/div[2]/ul/li[3]').extract()
items.append(item)
return items

谢谢!

最佳答案

您的问题有两个级别。

1. 禁用 JS 后 Bio url 不可用。在浏览器中关闭 JS 并检查此页面: https://votesmart.org/candidate/126288/derek-stanford

您应该会在注释下方看到带有空 href 和正确 url 的标签。

<a href="#" class="folder" id="folder-bio">
<!--<a href='/candidate/biography/126288/derek-stanford' itemprop="url" class='more'>
See Full Biographical and Contact Information</a>-->

对于提取bio url,你可以用xpath选择器“/comment()”得到这个评论,然后用正则表达式提取url。

或者,如果 url 结构对于所有页面都是通用的,只需自己构建 url:将链接中的“/candidate/”替换为“/candidate/biography/”。

NB! If you face unexpected issues, one of the first actions - disable JS and look at the page as Scrapy see it. Test all selectors.


2. 您对元素的使用非常复杂。如果“一个项目=一个人”,你应该只在“parse_person”中定义一个项目并将其传递给“parse_bio”。

查看更新后的代码。我在发现问题时重写了一些部分。备注:

  • 您不需要(在大多数情况下)创建“项目”列表并将项目附加到其中。 Scrapy 管理项目本身。
  • "sel = Selector(response)"在你的代码中没有意义,你可以扔掉它。

此代码已使用 Scrapy 1.0 和 Python 3.5 进行测试,但早期版本应该也能正常工作。

from scrapy import Spider, Request

class VSSpider(Spider):
name = "vs5"
allowed_domains = ["votesmart.org"]
start_urls = ["https://votesmart.org/officials/WA/L/washington-state-legislative"]

def parse(self, response):
for href in response.css('h5 a::attr(href)').extract():
person_url = response.urljoin(href)
yield Request(person_url, callback=self.parse_person)

def parse_person(self, response): # former "parse1"
# define item, one for both parse_person and bio function
item = LegislatorsItems()

# extract text from left menu table and populate to item
desc_rows = response.css('.span-abbreviated td::text').extract()
if desc_rows:
item['current_office'] = desc_rows[0]
item['running_for'] = desc_rows[1] if len(desc_rows) > 1 else None

# create right bio url and pass item to it
bio_url = response.url.replace('votesmart.org/candidate/',
'votesmart.org/candidate/biography/')
return Request(bio_url, callback=self.parse_bio, meta={'item': item})

def parse_bio(self, response): # former "parse2"
# get item from meta, add "tester" data and return
item = response.meta['item']
item['tester'] = response.css('.item.first').xpath('//li[3]').extract()
print(item) # for python 2: print item
return item

关于python - 在 scrapy 中产生项目和回调请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39261636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com