Scrapy 用于解析 html 页面。我的问题是为什么有时scrapy会返回我想要的响应,但有时却不返回响应。是我的错吗?这是我的解析函数:
class AmazonSpider(BaseSpider):
name = "amazon"
allowed_domains = ["amazon.org"]
start_urls = [
"http://www.amazon.com/s?rh=n%3A283155%2Cp_n_feature_browse-bin%3A2656020011"
]
def parse(self, response):
sel = Selector(response)
sites = sel.xpath('//div[contains(@class, "result")]')
items = []
titles = {'titles': sites[0].xpath('//a[@class="title"]/text()').extract()}
for title in titles['titles']:
item = AmazonScrapyItem()
item['title'] = title
items.append(item)
return items
最佳答案
我相信您只是没有使用最合适的 XPath 表达式。
Amazon 的 HTML 有点乱,不是很统一,因此不太容易解析。但经过一些试验后,我可以使用以下 parse
函数提取几个搜索结果的所有 12 个标题:
def parse(self, response):
sel = Selector(response)
p = sel.xpath('//div[@class="data"]/h3/a')
titles = p.xpath('span/text()').extract() + p.xpath('text()').extract()
items = []
for title in titles:
item = AmazonScrapyItem()
item['title'] = title
items.append(item)
return items
如果您关心结果的实际顺序,上述代码可能不合适,但我相信情况并非如此。
关于Python Scrapy 并不总是从网站下载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20289450/