Python crawler: How to crawl paging data ?, Python Crawler
The previous article "Python crawler: crawling data where everyone is a product manager" describes how to crawl a single page of data. This article details how to crawl multiple pages of data.
Crawler object:
There are financial management project list page [performance] under the state of the first 10 pages of data, address: https://www.yrw.com/products/list-all-all-performance-1-createTimeDesc-1.html
Programming logic:
1. Find the page Address Change Pattern 2. parse the webpage, obtain the content, and put it into the custom function 3. Call the function and output the page content
Detailed explanation:
1. First, insert the databases used: BeautifulSoup and requests.
1 from bs4 import BeautifulSoup2 import requests
2. Observe the address change rules. As you can see, the number 1 in createtimedesc-1.html changes with the changes in the page. In this case, the address is stored in the list, followed by the format () and for loops to store multiple addresses.
1 urls = ['https://www.yrw.com/products/list-direct-all-performance-1-createTimeDesc-{}.html'.format(str(i)) for i in range(1,11)]2 print(urls)
Print the address to check whether it is correct. Here, range () is the address of the first 10 pages.
3. Next, define the resolution function. The initial value of the parameter data is null. The Content Used in the function is the same as that described in the previous article. Request urls first, then use BeautifulSoup to parse and filter the position of the project title titles for output.
1 def get_titles(urls,data = None):2 web_data = requests.get(urls)3 soup = BeautifulSoup(web_data.text, 'lxml')4 titles = soup.select(' h3 > a > em > strong')5 for title in titles:6 data = {7 'title': title.get_text()8 }9 print(data)
4. Finally, let's call the function.
1 for titles in urls:2 get_titles(titles)
Complete code:
1 from bs4 import BeautifulSoup 2 import requests 3 4 urls = ['https://www.yrw.com/products/list-direct-all-performance-1-createTimeDesc-{}.html'.format(str(i)) for i in range(1,11)] 5 # print(urls) 6 7 def get_titles(urls,data = None): 8 web_data = requests.get(urls) 9 soup = BeautifulSoup(web_data.text, 'lxml')10 titles = soup.select(' h3 > a > em > strong')11 for title in titles:12 data = {13 'title': title.get_text()14 }15 print(data)16 17 for titles in urls:18 get_titles(titles)
Running result(Only show part ):
{'Title': 'zt321 '}
{'Title': 'supply chain ZT2923 '}
{'Title': 'Car rental ZT335 '}
{'Title': 'supply chain ZT2922 '}
{'Title': 'supply chain ZT2919 '}
Operating Environment: Python version, 3.6; PyCharm version, 2016.2; Computer: Mac
----- End -----
Author: du wangdan, Public Account: du wangdan, Internet product manager.