【发布时间】:2018-04-03 20:05:09
【问题描述】:
我正在尝试找到一种有效的方法来抓取 BS4 中的多个页面。我能够轻松地抓取第一页并获取我需要的所有数据,但不幸的是,并非所有数据都在上面。还有 2 个其他页面要抓取,而不是硬编码并更改第二页和第三页的 URL,我想知道是否有使用 BS4 在 Python 中执行此操作的更优雅的方法。 URL 中唯一需要更改的部分是 page=1 到相应的页码(1、2、3)。
import csv
import requests
from bs4 import BeautifulSoup
url = "https://www.congress.gov/members?q={%22congress%22:%22115%22}&pageSize=250&page=1"
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
names = soup.find_all()
items = soup.find_all("li","expanded")
for item in items:
print(item.text)
print(item.find("a"))
with open('web.csv', 'a') as csv_file:
writer = csv.writer(csv_file)
writer.writerow([item.find("a").encode('utf-8')])
【问题讨论】:
标签: python python-3.x web-scraping beautifulsoup