gpt4 book ai didi

python - 使用Scrapy解析站点,跟随Next Page,写成XML

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:58 25 4
gpt4 key购买 nike

当我评论一段代码时,我的脚本运行得非常好:返回

这是我的代码,更改为 http://example.com因为这似乎是其他人可能为了维护“抓取”合法性问题所做的事情。

class Vfood(CrawlSpider):
name = "example.com"
allowed_domains = [ "example.com" ]
start_urls = [
"http://www.example.com/TV_Shows/Show/Episodes"
]

rules = (
Rule(SgmlLinkExtractor(allow=('example\.com', 'page='), restrict_xpaths = '//div[@class="paginator"]/
span[@id="next"]'), callback='parse'),
)

def parse(self, response):
hxs = HtmlXPathSelector(response)
items = []
countries = hxs.select('//div[@class="index-content"]')
tmpNextPage = hxs.select('//div[@class="paginator"]/span[@id="next"]/a/@href').extract()
for country in countries:
item = FoodItem()
countryName = country.select('.//h3/text()').extract()
item['country'] = countryName
print "Country Name: ", countryName
shows = country.select('.//div[@class="content1"]')
for show in shows.select('.//div'):
showLink = (show.select('.//h4/a/@href').extract()).pop()
showLocation = show.select('.//h4/a/text()').extract()
showText = show.select('.//p/text()').extract()
item['showURL'] = "http://www.travelchannel.com"+str(showLink)
item['showcity'] = showLocation
item['showtext'] = showText
item['showtext'] = showText
print "\t", showLink
print "\t", showLocation
print "\t", showText
print "\n"
items.append(item)
**#return items**

for NextPageLink in tmpNextPage:
m = re.search("Location", NextPageLink)
if m:
NextPage = NextPageLink
print "Next Page: ", NextPage
yield Request("http://www.example.com/"+NextPage, callback = self.parse)
else:
NextPage = 'None'
SPIDER = food()

如果我取消注释 #return 项目,我会收到以下错误:

yield Request("http://www.example.com/"+NextPage, callback = self.parse)
SyntaxError: 'return' with argument inside generator

通过留下评论,我无法收集 XML 格式的数据,但根据打印语句的结果,我确实在屏幕上看到了我应该看到的所有内容。

我获取 xml 的命令:

scrapy crawl example.com --set FEED_URI=food.xml --set FEED_FORMAT=xml

当我取消注释上面的 return items 行时,我创建了 XML 文件,但脚本停止并且不会跟随链接。

最佳答案

您正在返回一个项目列表(可能在错误的位置),随后在同一函数中您使用 yield 来生成请求。您不能在 Python 中像这样混合使用 yield 和 return。

要么将所有内容添加到列表中并在解析方法结束时返回它,要么在所有地方使用 yield。我的建议是将 items.append(item) 替换为 yield item 并删除对项目列表的所有引用。

关于python - 使用Scrapy解析站点,跟随Next Page,写成XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6529630/

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