Python+Selenium — 爬取京东搜索商品页数据
生活随笔
收集整理的這篇文章主要介紹了
Python+Selenium — 爬取京东搜索商品页数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用 request 下載京東搜索商品頁面源碼后,發現得到的數據只有30條,懷疑京東搜索頁面加載方式應該是動態渲染的,所以打算采用 Selenium 驅動谷歌瀏覽器來爬取搜索頁面。
代碼如下:
from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from lxml import etree import time import csvclass JDSelenium():def __init__(self,keyword,page,timeout=10,service_args=['--load-images=false', '--disk-cache=true']):self.keyword = keywordself.timeout = timeoutself.page = pageself.chrome_options = webdriver.ChromeOptions()self.chrome_options.add_argument('--headless')self.browser = webdriver.Chrome(chrome_options=self.chrome_options,service_args=service_args)self.browser.set_page_load_timeout(self.timeout)# 可以選擇加載瀏覽器# self.browser = webdriver.Chrome()self.wait = WebDriverWait(self.browser,self.timeout)self.url = r'https://search.jd.com/Search?keyword={keyword}&enc=utf-8&page={page}'self.file = open('{keyword}.csv'.format(keyword=self.keyword),'w',newline='')self.write = self.create_writer()self.count = 0def close(self):self.browser.close()self.file.close()def create_writer(self):fieldnames = ['Title','Store','Price','Comments']writer = csv.DictWriter(self.file,fieldnames=fieldnames) writer.writeheader()return writerdef process_request(self,page):try:self.browser.get(self.url.format(keyword=self.keyword,page=page))self.wait.until(EC.presence_of_element_located((By.CLASS_NAME,"pn-next")))self.browser.execute_script('window.scrollTo(0,document.body.scrollHeight)')time.sleep(5)return etree.HTML(self.browser.page_source)#出現異常可以選擇關閉,也可以選擇繼續執行except Exception as e:print(e)# self.process_request(page)self.close()def process_item(self,response):products = response.xpath('//*[@id="J_goodsList"]/ul//li[@class="gl-item"]')for product in products:item = {}if '自營' in product.xpath('.//div[@class="p-icons"]//i//text()'):#這里只爬取自營店的數據#分析頁面發現有些商品雖是自營店的,但沒有出現店名,所以采用 join() 拼接列表,防止出現空列表而報錯的情況item['Store'] = ''.join(product.xpath('.//div[@class="p-shop"]/span/a/text()'))item['Title'] = ''.join(product.xpath('.//div[contains(@class,"p-name")]/a/em//text()'))item['Price'] = product.xpath('.//div[@class="p-price"]/strong/i/text()')[0]item['Comments'] = product.xpath('.//div[@class="p-commit"]/strong/a/text()')[0]self.count += 1self.write.writerow(item) else:continuedef run(self):for page in range(1,self.page+1):print('------正在爬取第{page}頁------'.format(page=page))response = self.process_request(2*page-1)self.process_item(response)print('數據保存完成')self.close()print('共爬取到{count}條數據'.format(count=self.count))if __name__ == '__main__':jd = JDSelenium(keyword='電腦',page=1)jd.run()這里沒有通過 selenium 獲取需要的信息,而是等頁面加載完成后通過網頁源代碼抽取需要的信息。其實本來是想寫成 Scrapy+Selenium 的,但嫌棄 scrapy 框架太麻煩了,所以整合到一塊了。
ps:由于請求鏈接后,需要等頁面加載一部分然后滾動頁面,最后再等待加載完成,耗費一點時間,所以爬取過程有點慢。*
總結
以上是生活随笔為你收集整理的Python+Selenium — 爬取京东搜索商品页数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Unity动画分层和遮罩
- 下一篇: Python控制台英汉-汉英电子词典(代