下面的代码通过“下一步”按钮链接进行实际分页。
from bs4 import BeautifulSoup
import requests, urllib.parse
import lxml
def print_extracted_data_from_url(url):
headers = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
response = requests.get(url, headers=headers).text
soup = BeautifulSoup(response, 'lxml')
print(f'Current page: {int(soup.select_one(".YyVfkd").text)}')
print(f'Current URL: {url}')
print()
for container in soup.findAll('div', class_='tF2Cxc'):
head_text = container.find('h3', class_='LC20lb DKV0Md').text
head_sum = container.find('div', class_='IsZvec').text
head_link = container.a['href']
print(head_text)
print(head_sum)
print(head_link)
print()
return soup.select_one('a#pnnext')
def scrape():
next_page_node = print_extracted_data_from_url(
'https://www.google.com/search?hl=en-US&q=coca cola')
while next_page_node is not None:
next_page_url = urllib.parse.urljoin('https://www.google.com', next_page_node['href'])
next_page_node = print_extracted_data_from_url(next_page_url)
scrape()
部分输出:
Results via beautifulsoup
Current page: 1
Current URL: https://www.google.com/search?hl=en-US&q=coca cola
The Coca-Cola Company: Refresh the World. Make a Difference
We are here to refresh the world and make a difference. Learn more about the Coca-Cola Company, our brands, and how we strive to do business the right way.Careers · Contact Us · Jobs at Coca-Cola · Our Company
https://www.coca-colacompany.com/home
Coca-Cola
2021 The Coca-Cola Company, all rights reserved. COCA-COLA®, "TASTE THE FEELING", and the Contour Bottle are trademarks of The Coca-Cola Company.
https://www.coca-cola.com/
或者,您可以使用来自 SerpApi 的 Google Search Engine Results API 来执行此操作。这是一个带有免费计划的付费 API。
要集成的代码:
import os
from serpapi import GoogleSearch
def scrape():
params = {
"engine": "google",
"q": "coca cola",
"api_key": os.getenv("API_KEY"),
}
search = GoogleSearch(params)
results = search.get_dict()
print(f"Current page: {results['serpapi_pagination']['current']}")
for result in results["organic_results"]:
print(f"Title: {result['title']}\nLink: {result['link']}\n")
while 'next' in results['serpapi_pagination']:
search.params_dict["start"] = results['serpapi_pagination']['current'] * 10
results = search.get_dict()
print(f"Current page: {results['serpapi_pagination']['current']}")
for result in results["organic_results"]:
print(f"Title: {result['title']}\nLink: {result['link']}\n")
scrape()
部分输出:
Results from SerpApi
Current page: 1
Current URL: https://www.google.com/search?hl=en-US&q=coca cola
The Coca-Cola Company: Refresh the World. Make a Difference
We are here to refresh the world and make a difference. Learn more about the Coca-Cola Company, our brands, and how we strive to do business the right way.Careers · Contact Us · Jobs at Coca-Cola · Our Company
https://www.coca-colacompany.com/home
Coca-Cola
2021 The Coca-Cola Company, all rights reserved. COCA-COLA®, "TASTE THE FEELING", and the Contour Bottle are trademarks of The Coca-Cola Company.
https://www.coca-cola.com/
免责声明,我为 SerpApi 工作。