这是我用来从到到网上抓取电子邮件地址和餐馆名称的蜘蛛
import scrapy
class RestaurantSpider(scrapy.Spider):
name = 'tripadvisorbot'
start_urls = [
'https://www.tripadvisor.com/Restaurants-g188633-The_Hague_South_Holland_Province.html#EATERY_OVERVIEW_BOX'
]
def parse(self, response):
for listing in response.xpath('//div[contains(@class,"__cellContainer--")]'):
link = listing.xpath('.//a[contains(@class,"__restaurantName--")]/@href').get()
text = listing.xpath('.//a[contains(@class,"__restaurantName--")]/text()').get()
complete_url = response.urljoin(link)
yield scrapy.Request(
url=complete_url,
callback=self.parse_listing,
meta={'link': complete_url,'text': text}
)
next_url = response.xpath('//*[contains(@class,"pagination")]/*[contains(@class,"next")]/@href').get()
if next_url:
yield scrapy.Request(response.urljoin(next_url), callback=self.parse)
def parse_listing(self, response):
link = response.meta['link']
text = response.meta['text']
email = response.xpath('//a[contains(@href, "mailto:")]/@href').get()
yield {'Link': link,'Text': text,'Email': email}
我在Anaconda提示符下运行下面的命令行,运行上面的Spider并将其保存为json文件
scrapy crawl tripadvisorbot -O tripadvisor.json
没有数据被擦除,创建了一个json文件,但它是空的。
我不知道是什么问题,我是一个新的网页抓取和Python编码一般。所有的帮助将不胜感激
谢谢
1条答案
按热度按时间xcitsw881#
在我的计算机上,HTML中没有
_cellContainer--
和__restaurantName--
类。Page使用随机字符作为类名。
但是每一项都直接在
<div data-test-target="restaurants-list">
的div中,我用它来获取所有项。后来我得到了第一个
<a>
(它有图像,而不是name
),我跳过了text
和complete_url
,而是直接运行reponse.follow(link)
。当我看到包含详细信息的页面时,我会得到
reponse.url
,得到complete_url
,得到h1
,得到text
您可以将所有代码放在一个文件中,然后运行
python script.py
,而无需创建项目。部分结果: