Use selenium to capture Taobao product information
This time I will bring you the use of selenium to capture Taobao product information. What are the precautions for using selenium to capture Taobao product information? The following is a practical case, let's take a look.
Taobao pages use a lot of js to load data, so it is easier to use selenium to crawl. As a testing tool, selenum is mainly used with the windowless browser phantomjs.import re from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from pyquery import PyQuery as pq ''' wait.until()语句是selenum里面的显示等待,wait是一个WebDriverWait对象,它设置了等待时间,如果页面在等待时间内 没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常,也可以说程序每隔xx秒看一眼,如果条件 成立了,则执行下一步,否则继续等待,直到超过设置的最长时间,然后抛出TimeoutException 1.presence_of_element_located 元素加载出,传入定位元组,如(By.ID, 'p') 2.element_to_be_clickable 元素可点击 3.text_to_be_present_in_element 某个元素文本包含某文字 ''' # 定义一个无界面的浏览器 browser = webdriver.PhantomJS( service_args=[ '--load-images=false', '--disk-cache=true']) # 10s无响应就down掉 wait = WebDriverWait(browser, 10) #虽然无界面但是必须要定义窗口 browser.set_window_size(1400, 900) def search(): ''' 此函数的作用为完成首页点击搜索的功能,替换标签可用于其他网页使用 :return: ''' print('正在搜索') try: #访问页面 browser.get('https://www.taobao.com') # 选择到淘宝首页的输入框 input = wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, '#q')) ) #搜索的那个按钮 submit = wait.until(EC.element_to_be_clickable( (By.CSS_SELECTOR, '#J_TSearchForm > p.search-button > button'))) #send_key作为写到input的内容 input.send_keys('面条') #执行点击搜索的操作 submit.click() #查看到当前的页码一共是多少页 total = wait.until(EC.presence_of_element_located( (By.CSS_SELECTOR, '#mainsrp-pager > p > p > p > p.total'))) #获取所有的商品 get_products() #返回总页数 return total.text except TimeoutException: return search() def next_page(page_number): ''' 翻页函数, :param page_number: :return: ''' print('正在翻页', page_number) try: #这个是我们跳转页的输入框 input = wait.until(EC.presence_of_element_located( (By.CSS_SELECTOR, '#mainsrp-pager > p > p > p > p.form > input'))) #跳转时的确定按钮 submit = wait.until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#mainsrp-pager > p > p > p > p.form > span.J_Submit'))) #清除里面的数字 input.clear() #重新输入数字 input.send_keys(page_number) #选择并点击 submit.click() #判断当前页是不是我们要现实的页 wait.until( EC.text_to_be_present_in_element( (By.CSS_SELECTOR, '#mainsrp-pager > p > p > p > ul > li.item.active > span'), str(page_number))) #调用函数获取商品信息 get_products() #捕捉超时,重新进入翻页的函数 except TimeoutException: next_page(page_number) def get_products(): ''' 搜到页面信息在此函数在爬取我们需要的信息 :return: ''' #每一个商品标签,这里是加载出来以后才会拿网页源代码 wait.until(EC.presence_of_element_located( (By.CSS_SELECTOR, '#mainsrp-itemlist .items .item'))) #这里拿到的是整个网页源代码 html = browser.page_source #pq解析网页源代码 doc = pq(html) items = doc('#mainsrp-itemlist .items .item').items() for item in items: # print(item) product = { 'image': item.find('.pic .img').attr('src'), 'price': item.find('.price').text(), 'deal': item.find('.deal-cnt').text()[:-3], 'title': item.find('.title').text(), 'shop': item.find('.shop').text(), 'location': item.find('.location').text() } print(product) def main(): try: #第一步搜索 total = search() #int类型刚才找到的总页数标签,作为跳出循环的条件 total = int(re.compile('(\d+)').search(total).group(1)) #只要后面还有就继续爬,继续翻页 for i in range(2, total + 1): next_page(i) except Exception: print('出错啦') finally: #关闭浏览器 browser.close() if name == 'main': main()I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
Detailed explanation of the use of Express and Koa2
JS imitation of the home page interface of Toutiao mobile terminal
Vue enumeration type implements HTML
The above is the detailed content of Use selenium to capture Taobao product information. For more information, please follow other related articles on the PHP Chinese website!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Notepad++7.3.1
Easy-to-use and free code editor