日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python+Selenium — 爬取京东搜索商品页数据

發布時間:2024/3/26 python 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 — 爬取京东搜索商品页数据的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。