先看一下代码,真的只是五十行:

 1 # coding=gbk
 2 
 3 from selenium import webdriver
 4 import time
 5 
 6 options = webdriver.ChromeOptions()
 7 options.add_argument(r'--user-data-dir=C:\Users\lwy\AppData\Local\Google\Chrome\User Data\Default')
 8 options.add_experimental_option('excludeSwitches', ['enable-automation'])
 9 driver = webdriver.Chrome(options=options)
10 driver.get('https://www.taobao.com/')
11 
12 
13 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
14            'Referer': 'https://www.taobao.com/'}
15 
16 
17 def request_page():
18     driver.find_element_by_xpath('//*[@>)
19     time.sleep(3)
20     driver.find_element_by_xpath('//*[@>).click()
21     time.sleep(5)
22     # 控制页数
23     for i in range(5):
24         # 获取每页存放所有商品的div
25         all_thing_div = driver.find_element_by_xpath('//*[@>)
26         # 获取每个商品的div列表
27         thing_div_list = all_thing_div.find_elements_by_xpath('./div')
28         # 依次获取每个商品的信息
29         for thing_div in thing_div_list:
30             info_div_list = thing_div.find_element_by_css_selector('.ctx-box').find_elements_by_xpath(
31                 './div')  # 获取每个商品下面信息的4个div
32             price = info_div_list[0].find_element_by_xpath('./div[1]/strong').text  # 单价
33             customer = info_div_list[0].find_element_by_xpath('./div[@class="deal-cnt"]').text  # 购买数量
34             thing_name = info_div_list[1].find_element_by_xpath('./a').text
35             thing_lianjie = info_div_list[1].find_element_by_xpath('./a').get_attribute('href')
36             store_name = info_div_list[2].find_element_by_xpath('./div[1]/a/span[2]').text
37             store_where = info_div_list[2].find_element_by_xpath('./div[2]').text
38             print("单价:", price, "购买数量:", customer, '商品名称:', thing_name, '店铺名称:', store_name, '店铺所在地', store_where,
39                   '链接:', thing_lianjie)
40         print('第{0}页爬取完成'.format(i+1))
41         if i+1 == 5:
42             break
43         driver.find_element_by_xpath('//*[@>).click()
44         time.sleep(10)
45 
46 
47 if __name__ == '__main__':
48     request_page()
49     driver.close()

第七行用来加载chrome的配置文件,需要改成自己的路径,可以再chrome的地址栏里输入chrome://version查看,第八行用来绕过淘宝对selenium的检测,request_page是自定义的爬虫函数,主要是利用xpath语法,真的不要太方便,第一个for循环用来控制爬取的页数,第二个for循环用来爬取每一个商品。

(ps:还是正在努力的小菜鸡,希望大佬执教,,xixiiixi。。。。)

**********不积跬步无以至千里**********

相关文章:

  • 2021-07-02
  • 2022-02-26
  • 2021-12-13
  • 2021-07-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-08
  • 2021-10-11
  • 2021-08-23
  • 2022-02-18
  • 2021-12-29
  • 2021-12-13
  • 2021-12-10
相关资源
相似解决方案