本篇通过一个案例分享Xpath和Beautifulsoup的用法,后续会整理一些之前写过的实例。
本文分享爬取的是某区生态环境局行政处罚结果公示,包括点击公司名称后跳转的子页面表格。
import pandas as pd
from selenium import webdriver
from lxml import etree
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.service import Service
s = Service('chromedriver.exe')
option = webdriver.ChromeOptions()
option.add_argument("headless")
browser = webdriver.Chrome(service=s, options=option)
table = pd.DataFrame()
for page in range(1, 37):
url = f'https://www.bjxch.gov.cn/zt/xzxkhxzcfgszl/syx/jglb/pnleixingpvxzcfjggspnidpv752pnpagenumpv{page}.html'
browser.get(url)
content = browser.page_source
link_list = etree.HTML(content).xpath('//div[@class="list"]//a/@href')
for link in link_list:
new_url = f'https://www.bjxch.gov.cn{link}'
browser.get(new_url)
content_text = browser.page_source
soup = BeautifulSoup(content_text, 'lxml')
detail = [item.string for item in soup.select('td')]
detail_dic = dict(zip(detail[0::2], detail[1::2]))
table = table.append(detail_dic, ignore_index=True)
table.to_csv("xichengqu.csv", index=False)
(由于是一年前写的代码,可能网站开发更新会有一些变动,代码仅供参考),如有不准确欢迎评论区讨论,致谢~