1.写爬虫最重要的一步就是解析需要抓取信息的xpath,我是比较习惯使用这个。大家可以安装一个xpath helper
2. 第一步上代码,我用的是jupyter notebook 以便边看html代码,边测试。
from selenium.webdriver import ChromeOptions
import time
from fake_useragent import UserAgent
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
#ua = UserAgent()
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_experimental_option('useAutomationExtension', False)
NoImage = {"profile.managed_default_content_settings.images": 2} # 控制 没有图片
option.add_experimental_option("prefs", NoImage)
# option.add_argument(f'user-agent={ua.chrome}') # 增加浏览器头部
# chrome_options.add_argument(f"--proxy-server=http://{self.ip}") # 增加IP地址。。
# option.add_argument('--headless') #无头模式 不弹出浏览器
browser = webdriver.Chrome(options=option,executable_path=r"D:\Python3.7.6\Scripts\chromedriver.exe")
browser.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
'source': 'Object.defineProperty(navigator,"webdriver",{get:()=>undefined})'
}) #去掉selenium的驱动设置
browser.set_window_size(1200,768)
wait = WebDriverWait(browser, 12)
url='https://www.amazon.com/reviews/top-reviewers'
browser.get(url)
运行之后,自己手动更改邮编,刷新一下,这里在抓取其他产品信息比较重要,这里不改邮编好像详细一样的。
3、我需要抓取的信息在这个tbody
html_code = browser.page_source
将网页代码拿下来。
拿到这个信息
4、由于客户信息详情页都有,这里,我只获取详情页的链接即可
通过for循环,即可获取全部的用户界面
from scrapy.selector import Selector
selector=Selector(text=html_code)
tbody=selector.xpath('//*[@id="pha-lb-page"]/div[2]/div/div/table/tbody//tr')
for each in tbody:
link=each.xpath('./td[3]/a[1]/@href').extract()
if link:
print(link)
5、这里构造链接,进入详情页,然后抓取信息。
one_desc='https://www.amazon.com/gp/profile/amzn1.account.AHXGA4UF6GOLITRL2DCUR63BTRPA/ref=cm_cr_tr_tbl_59_name'
js1 = f" window.open('{one_desc}')" # 执行打开新的标签页
browser.execute_script(js1) # 打开新的网页标签
browser.switch_to.window( browser.window_handles[-1])
前面控制没有图片,注释掉了,这里要抓取这些信息
html_code_desc = browser.page_source
selector_desc=Selector(text=html_code_desc)
concat=selector_desc.xpath('//*[@id="profile_v5"]/div/div/div[4]/div[1]/div[3]/div[2]/div/div/div[4]/div//@href').extract()
desc_review=selector_desc.xpath('//*[@id="profile_v5"]/div/div/div[4]/div[2]/div[1]/div[2]/div//text()').extract()
没改邮编,默认的是汉语,
6、
下面就是用scrapy 框架 整和代码