Table of Contents
Introduction: " >Introduction:
Case implementation: " > Case implementation:
Advanced:
Home Backend Development Python Tutorial Detailed explanation of how to use python crawler tool Selenium

Detailed explanation of how to use python crawler tool Selenium

Mar 08, 2017 am 11:25 AM
python crawler

Introduction:

Ordinary urllib2 cannot be implemented when using python to crawl dynamic pages. For example, on the JD.com homepage below, new content will be loaded as the scroll bar is pulled down. , and urllib2 cannot crawl this content. At this time, today's protagonist selenium is needed.

Detailed explanation of how to use python crawler tool Selenium

Selenium is a tool for web application testing. Selenium tests run directly in the browser, just like real users. Supported browsers include IE, Mozilla Firefox, Mozilla Suite, etc. It is also very convenient to use it to crawl pages. You only need to follow the access steps to simulate a human operation. You don’t have to worry about Cookie and Session processing at all. It can even help you enter your account and password, and then click the login button. For the scroll above bar, you just need to scroll the browser to the bottom and save the page. The above functions are very useful when dealing with some anti-crawler mechanisms. Next, we will start the main text of our explanation and lead you to crawl a dynamic web page that requires login.

Case implementation:

To use Selnium, you need to select a calling browser and download the corresponding driver. In the desktop version, you can choose Chrome. FireFox, etc., you can use PhantomJS on the server side, and the desktop version can be directly called up in the browser to observe the changes, so generally we can change the browser to PhantomJS after debugging the desktop version with Chrome, etc. and then upload it to the server to run it, here We directly use PhantomJS for demonstration.

First import the module:

 from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
 from selenium import webdriver
Copy after login

Continue Initialize a browser when coming down. You can specify some attributes of the loaded web page in the parameters:

cap = webdriver.DesiredCapabilities.PHANTOMJS
cap["phantomjs.page.settings.resourceTimeout"] = 180
cap["phantomjs.page.settings.loadImages"] = False

driver = webdriver.PhantomJS(executable_path="/home/gaorong/phantomjs-2.1.1-linux-x86_64/bin/phantomjs", desired_capabilities=cap)
Copy after login

The above initializes PhantomJS and sets the path of the browser. The loading attribute selects the resource loading timeout. and don't load images (we only care about web text). You can also choose other settings here.

Set some properties and download a web page

driver.set_page_load_timeout(180)     
driver.get('http://www.php.cn/')
time.sleep(5)
driver.save_screenshot('./login.png')   #为便于调试,保存网页的截图
Copy after login

Since errors are inevitable when running on the server side, you can use save_screenshot to save the current web page for easy debugging.

The next step is to enter your account and password to log in to obtain the cookies of the website for subsequent requests.

#输入username和password 
driver.find_element_by_xpath("/html/body/div[1]/div[1]/login/div[2]/div/form/input[1]").send_keys('*****')   
time.sleep(1)
print 'input user success!!!'

driver.find_element_by_xpath("/html/body/div[1]/div[1]/login/div[2]/div/form/input[2]").send_keys('****')
time.sleep(1)
print 'input password success!!!'

driver.find_element_by_xpath("/html/body/div[1]/div[1]/login/div[2]/div/form/button").click()
time.sleep(5)
Copy after login

The above code uses find_element_by_xpath to get the location of the input box, enter the account and password, and click the login button. You can see that it is very convenient. It will automatically jump to the next page, we just need to sleep for a few seconds and wait for it.

The web page information we need to crawl is in a specific element, so we need to determine whether this element appears:

try:
     element = WebDriverWait(driver, 10).until(
         EC.presence_of_element_located((By.CLASS_NAME, 'pulses'))
     )
     print 'find element!!!'        
 except:
     print 'not find element!!!'
     print traceback.format_exc()
     driver.quit()
Copy after login

The above determines whether the element with class 'pulse' appears. If it does not appear after waiting for 10 seconds, selenum will cause a TimeoutError error.

Basic initialization has been carried out above, and then dynamic content needs to be processed. This web page, like JD.com, will automatically appear content with the pull-down, so we need to implement the drop-down scroll bar:

print 'begin scroll to get info page...'
t1 = time.time()
n = 60   #这里可以控制网页滚动距离
for i in range(1,n+1):
    s = "window.scrollTo(0,document.body.scrollHeight/{0}*{1});".format(n,i)
    #输出滚动位置,网页大小,和时间
    print s, len(driver.page_source),time.time()-t1
    driver.execute_script(s)
    time.sleep(2)
Copy after login

where driver.page_source is to get the text of the web page. When the scrolling is complete we can call it and write it to a file. This completes the program logic.

Advanced:

Using selenim can deal with common anti-crawler strategies, because it is equivalent to a person browsing the web, but additional processing is required for verification codes. , and another point is that the access speed cannot be too fast. After all, it needs to call a browser. If it is too slow, we can use it when necessary. If not necessary, we can use the requests library to operate.

Here are two blogs that you can refer to: Python Crawler Tool Five: Selenium Usage and Common Functions


The above is the detailed content of Detailed explanation of how to use python crawler tool Selenium. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles