python crawling data
1、静态网页爬虫
1.1 使用requests 库进行爬去网页数据后,使用Beautiful Soup 进行解析。试用于静态网页(html)网页数据的爬取。
示例:
import requests
def getHTMLText(url):
try:
kv={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393'}
r=requests.get(url,headers=kv,timeout=30)
r.raise_for_status() # if the status is not 200,then there will be an exeption
r.encoding= r.apparent_encoding # change the encoding to show Chinese
return r.text
except:
return "exception"
StartEnd=input("please input order:")
url="https://item.jd.com/3995645.html"
if StartEnd=="start" :
print(getHTMLText(url))
else:
print("wrong order")
2、动态网页爬虫
方法一:
工具: chrome浏览器+python
网页地址: https://quote.eastmoney.com/center/gridlist.html#hs_a_board
方法:
1、’打开想要爬取的网页地址,在浏览器上右键,选择“”检查“,,进入网络选项,找到对应接口(根据接口preview内容判定是否是自己想要的接口)
2、点击底部不同的分页后,查看对应的接口的headers中的“Request URL:”对应的内容判断 传入的参数的信息。
方法二:
前提:安装selenium +chromedriver+chrome ,并且确保 安装的selenium版本和chromedriver、chrome版本兼容。(建议使用:selenium的版本为Version: 3.141.0) chromedriver 和chrome版本必须兼容。(注:必须关闭chrome自动更新,防止chrome自动更新后 安装的chromedriver版本不一致。 mac关闭 chrome的自动更新方法:在终端中输入:cd ~/Library/Application\ Support/Google && sudo mv GoogleUpdater GoogleUpdater.delete && touch GoogleUpdater && chmod 000 GoogleUpdater )
chromedriver 下载安装:Mac如何安装谷歌chromedriver驱动_mac怎么下载chromedriver-CSDN博客
在Mac中使用Anaconda安装Selenium,可以按照以下步骤进行:
- 打开Anaconda Prompt:在Mac上,你可能需要打开终端(Terminal)来模拟这个步骤,因为Anaconda Prompt是Windows特有的。在终端中,你可以通过激活你的Anaconda环境来执行命令。
- 检查是否已经安装了Selenium:在终端中,你可以通过输入
conda list
来查看当前已经安装的所有Python包。如果Selenium不在列表中,那么你就需要安装它。 - 安装Selenium:在终端中,输入conda
install selenium
来安装Selenium。如果你使用的是特定版本的Python(比如通过Anaconda创建的虚拟环境),你可能需要使用pip3
或者指定Python版本的pip命令(比如python3 -m pip install selenium
)。 - 安装ChromeDriver:Selenium需要与浏览器驱动(如ChromeDriver)一起使用才能控制浏览器。你需要下载与你的Chrome浏览器版本相对应的ChromeDriver。你可以在Chrome浏览器的设置中找到“关于Chrome”来查看你的浏览器版本,然后访问ChromeDriver的下载页面(如:https://sites.google.com/a/chromium.org/chromedriver/downloads)来下载相应版本的ChromeDriver。
- 配置ChromeDriver:下载并解压ChromeDriver后,你需要将其放在Python或者Anaconda可以找到的地方。通常,你可以将其放在Anaconda的bin目录中,或者将其添加到系统的PATH环境变量中。
mac 安装 ChromeDriver
- 打开终端。
- 进入根目录,输入命令
cd /
。 - 再进入
/usr/local/bin
目录,输入命令cd /usr/local/bin
。 - 将解压后的chromedriver执行文件放置到Python目录下(/usr/local/bin)
- 验证是否安装成功:在终端中输入“chromedriver --version”命令,检查安装是否成功
详细环境创建:(在终端命令窗口中依次执行)
1、conda create -n crawlenv2 python=3.12 #创建虚拟环境并安装3.12版本python
2、conda activate crawlenv2 #激活环境.
3、conda install pandas. #安装pandas
4、 conda install selenium=3.141.0 安装指定版本的selenium. ,匹配 urllib3版本1.26.2
5、conda remove urllib3 #卸载当前不兼容的urllib3
6、conda instal urllib3=1.26.2 # 重新安装指定版本的urllib3
完全删除anaconda后,重装:
1、应用程序中删除ananconda
2、找到ananconda文件夹删除
3、清除环境变量:
3.1 使用下面命令编辑环境变量文件,删除对应信息,后保存.
nano ~/.bash_profile
nano ~/.zshrc
3.2使用下面命令检查是否还存在conda环境变量
grep 'conda' ~/.bash_profile
grep 'conda' ~/.bashrc
grep 'conda' ~/.zshrc
3.2。
from selenium import webdriver
import time
import pandas as pd
# driver_path = 'C:\\Program Files (x86)\\Google\\Chrome\\Applicationchromedriver.exe' # 替换为你的chromedriver实际路径
browser=webdriver.Chrome()
#请求原始网页
browser.get('https://quote.eastmoney.com/center/gridlist.html#hs_a_board')
time.sleep(3) # 程序在这里暂停3秒,等待加载完成
#找到对应的菜单位置进行点击
browser.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[3]/ul/li[1]/a').click()
time.sleep(3) # 程序在这里暂停3秒,等待加载完成
# browser.find_element_by_xpath().click()
#定义空列表,存储对应的数据列表数据
dfs=[]
for i in range(281):
time.sleep(3)
data=browser.page_source #保存网页源文件数据
df=pd.read_html(data)[0]
browser.find_element_by_link_text("下一页").click()#找到下一页进行翻页
dfs.append(df) #当前页面数据添加到列表中
result=pd.concat(dfs)
result.to_excel('all_stocks20240505.xlsx')
browser.quit()
# print(result)
完整
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
import pandas as pd#reade stock code
df_code=pd.read_excel('./StockCode.xlsx',dtype={'code': str})
StockCode=df_code['code'][:2500]# 假设这是你从某处获得的动态参数 dfs=[] #定义空列表,存储对应的数据列表数据
dfs_error=[]#定义空列表,存储错误code# #请求原始网页
browser=webdriver.Chrome()
#get the detailsfor i in StockCode:#define websitecode=iurl = f'https://stockpage.10jqka.com.cn/{code}/company/#detail' #define website#请求原始网页browser.get(url)# wait = WebDriverWait(driver, 10)# time.sleep(10) # 程序在这里暂停3秒,等待加载完成#catch exceptiontry:#switch to frame 'dataifm'browser.switch_to_frame('dataifm')#locate the element# browser.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/table')WebDriverWait(browser, 3).until( EC.presence_of_element_located((By.XPATH, '/html/body/div[3]/div[3]/div[1]/div[2]/table')) ) data=browser.page_source #保存网页源文件数据#save the detailesdf=pd.read_html(data)[0]temporary_list =[code]+ df[1].tolist() + df[2].tolist()dfs.append(temporary_list)except (NoSuchElementException, TimeoutException) as e:dfs_error.append([code])continueexcept Exception as e:dfs_error.append([code])continueresult=pd.DataFrame(dfs)
result2=pd.DataFrame(dfs_error)# define table colomuns name
colomus_name=['code','CompName','CompName2','CommpName3','location','industry','website']
result.columns=colomus_name
result.to_excel('stock_detail20240525.xlsx')
result2.to_excel('stock_error20240525.xlsx')
# # print(result)
browser.quit()
报错处理: Timeout value connect was <object object at 0x000001F7C19945B0>, but it must be an int, float or NonePython中无法使用Selenium,显示ValueError: Timeout value connect was ……, but it must be an int, float or None-CSDN博客
报错:selenium.common.exceptions.TimeoutException: Message: timeout: Timed out receiving message from renderer: 0.733
(Session info: chrome=123.0.6312.58)
https://www.5axxw.com/questions/content/5sr6r0
报错:selenium chrome 报错 :错误代码:Out of Memory
import requests
import pandas as pd
#define the param of getApi
param={
'cb': 'jQuery112403932510994932017_1712314983198',
'pn': '4',
'pz': '20',
'po': '1',
'np': '1',
'ut': 'bd1d9ddb04089700cf9c27f6f7426281',
'fltt': '2',
'invt': '2',
'wbp2u': '|0|0|0|web',
'fid': 'f3',
'fs': 'm:0 t:6,m:0 t:80,m:1 t:2,m:1 t:23,m:0 t:81 s:2048',
'fields': 'f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152',
'_': '1712314983414'
}
#replace the headers of getApi to prevent failure
headers ={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36'
}
url='https://72.push2.eastmoney.com/api/qt/clist/get'
r=requests.get(url,params=param, headers=headers)
htmls=[]
htmls.append(r.text)
df=pd.read_html(htmls)
print(df)
from selenium import webdriver
import time
import pandas as pd
# driver_path = 'C:\\Program Files (x86)\\Google\\Chrome\\Applicationchromedriver.exe' # 替换为你的chromedriver实际路径
browser=webdriver.Chrome()
#请求原始网页
browser.get('https://quote.eastmoney.com/center/gridlist.html#hs_a_board')
time.sleep(3) # 程序在这里暂停3秒,等待加载完成
#找到对应的菜单位置进行点击
browser.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[3]/ul/li[1]/a').click()
time.sleep(3) # 程序在这里暂停3秒,等待加载完成
# browser.find_element_by_xpath().click()
#定义空列表,存储对应的数据列表数据
dfs=[]
for i in range(281):
time.sleep(3)
data=browser.page_source #保存网页源文件数据
df=pd.read_html(data)[0]
browser.find_element_by_link_text("下一页").click()#找到下一页进行翻页
dfs.append(df) #当前页面数据添加到列表中
result=pd.concat(dfs)
result.to_excel('all_stocks20240405.xlsx')
browser.quit()
# print(result)
import requests from bs4 import BeautifulSoup import datetime from lxml import etree import pandas as pd import os#define function to crawl the web def getHtmlText(url,hd):try:r=requests.get(url,headers=hd)r.raise_for_status()r.encoding=r.apparent_encodingreturn r.textexcept:return "exception" #define function to put the crawled data into a list #def fillJobList(jblist,html): # soup=BeautifulSoup(html,"html.parser") # p=re.compile(r'<span class="edu">(.*?)</span>',re.S) # item=re.findall(p,soup) # print(len(item)) # define function to save the data to excel def SaveData(jobinfo):#filetime=str(datetime.datetime.now()) #path="C:\Pythonpractice\crawled-data" #filepath=path+"'\'"+filetime+".xlsx" jobinfo.to_excel('C:\Pythonpractice\crawled-data\\20170907.xlsx', sheet_name='Sheet1')#print() #define main function def main(): jobcompany=[]jobname=[]jobsalary=[]jobarea=[]jobeducation=[]jobexperience=[]jobpulishtime=[]#jobinfo=pd.DataFrame({"jobcompany":jobcompany,"jobname":jobsalary,"joblocation":jobarea,"jobeducation":jobeducation,"jobexperience":jobexperience,"jobpulishtime":jobpulishtime}) hd={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393'}url="https://www.liepin.com/zhaopin/?industryType=industry_01&ckid=6efe03d17d7b4fa2&fromSearchBtn=2&industries=040&init=-1&salary=50$100&flushckid=1&headckid=d6096b0dc23b53b0" html=getHtmlText(url,hd) soup=BeautifulSoup(html,"html.parser")items=soup.find_all("div",class_="sojob-item-main clearfix")#print(len(items)) for i in range(len(items)):item=str(items[i])jbinfo=etree.XML(item)jbname=jbinfo.find(".//a[@data-promid]") #find all the a tag which has a "data-promid" atrribute jbsalary=jbinfo.find(".//span[@class='text-warning']")#find all the span tag its class's value is"text-warning" jbarea=jbinfo.find(".//*[@class='area']")jbedu=jbinfo.find(".//span[@class='edu']")jbexp=jbinfo.find(".//p[@class='condition clearfix']/span[last()]")#find all the last span the child of the p tag which has a "condition clearfix" class jbcomp=jbinfo.find(".//p[@class='company-name']/a")#find all a tag the children of the p tag which has a "company-name" class jbpulishtime=jbinfo.find(".//p[@class='time-info clearfix']/time")jobcompany.append(jbcomp.text.strip())jobname.append(jbname.text.strip())jobsalary.append(jbsalary.text.strip())jobarea.append(jbarea.text.strip())jobeducation.append(jbedu.text.strip())jobexperience.append(jbexp.text.strip())jobpulishtime.append(jbpulishtime.text.strip())jobinfo = pd.DataFrame({"jobcompany": jobcompany, "jobname":jobname ,"jobsalary":jobsalary, "joblocation": jobarea, "jobeducation": jobeducation,"jobexperience": jobexperience, "jobpulishtime": jobpulishtime})#jobinfo.to_excel('C:\Pythonpractice\crawled-data\\20170907.xlsx', sheet_name='Sheet1') print(jobinfo)SaveData(jobinfo)starttime = datetime.datetime.now() main() endtime = datetime.datetime.now() usetime=endtime-starttime print(usetime)
### 20241005 crawl data
from selenium import webdriver
import time
import pandas as pd
#参考地址:https://www.bilibili.com/video/BV16S4y1T7DV/?spm_id_from=333.999.0.0&vd_source=731ffa0519e33405606132cc5afc0ae0
# driver_path = 'C:\\Program Files (x86)\\Google\\Chrome\\Applicationchromedriver.exe' # 替换为你的chromedriver实际路径
browser=webdriver.Chrome()
#请求原始网页
# browser.get('https://quote.eastmoney.com/center/gridlist.html#hs_a_board') #市盈率
browser.get('https://quote.eastmoney.com/center/gridlist.html#hs_a_board') #总市值
time.sleep(3) # 程序在这里暂停3秒,等待加载完成
#找到对应的菜单位置进行点击--市净率
browser.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[3]/ul/li[1]/a').click()
time.sleep(3) # 程序在这里暂停3秒,等待加载完成
#选择总市值。
browser.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[4]/div[3]/select/option[2]').click()
time.sleep(3) # 程序在这里暂停3秒,等待加载完成
#定义空列表,存储对应的数据列表数据
dfs=[]
for i in range(283):
time.sleep(3)
data=browser.page_source #保存网页源文件数据
df=pd.read_html(data)[0]
browser.find_element_by_link_text("下一页").click()#找到下一页进行翻页
dfs.append(df) #当前页面数据添加到列表中
result=pd.concat(dfs)
result.to_excel("crawl/crawData/all_stocks_totalvalue20240924.xlsx")
browser.quit()
# print(result)
2025.04.19更新
craw the all stocks data
from selenium import webdriver
import time
import pandas as pd
from selenium.common.exceptions import NoSuchElementException
#参考地址:https://www.bilibili.com/video/BV16S4y1T7DV/?spm_id_from=333.999.0.0&vd_source=731ffa0519e33405606132cc5afc0ae0
# driver_path = 'C:\\Program Files (x86)\\Google\\Chrome\\Applicationchromedriver.exe' # 替换为你的chromedriver实际路径
browser=webdriver.Chrome()
#请求原始网页
# browser.get('https://quote.eastmoney.com/center/gridlist.html#hs_a_board') #市盈率
browser.get('https://quote.eastmoney.com/center/gridlist.html#hs_a_board') #总市值
time.sleep(3) # 程序在这里暂停3秒,等待加载完成
#找到对应的菜单位置进行点击--市净率
# 2025.01.20 网站更新了xpath地址 browser.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[3]/ul/li[1]/a').click()
# 2025.01.20 网站更新了xpath地址
browser.find_element_by_xpath('/html/body/div[1]/div[7]/div[2]/div/div/div[2]/ul/li[1]/a').click()
time.sleep(3) # 程序在这里暂停3秒,等待加载完成
#选择总市值。
# 2025.01.20 网站更新了xpath地址 browser.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[4]/div[3]/select/option[2]').click()
# 2025.01.20 网站更新了xpath地址
browser.find_element_by_xpath('/html/body/div[1]/div[7]/div[2]/div/div/div[3]/div[2]/div/select/option[2]').click()
time.sleep(5) # 程序在这里暂停3秒,等待加载完成
#定义空列表,存储对应的数据列表数据
dfs=[]
# for i in range(285):
# time.sleep(3)
# data=browser.page_source #保存网页源文件数据
# df=pd.read_html(data)[1]
# dfs.append(df) #当前页面数据添加到列表中
# if i!=284:
# browser.find_element_by_link_text(">").click()#找到下一页进行翻页
# 循环直到没有“下一页”按钮
while True:
time.sleep(3) # 等待页面加载
data = browser.page_source # 保存网页源文件数据
df = pd.read_html(data)[1] # 假设你需要的表格是第2个表格
dfs.append(df) # 当前页面数据添加到列表中
try:
# 尝试找到“>”按钮并点击
next_page_button = browser.find_element_by_link_text(">")
next_page_button.click()
except NoSuchElementException:
# 如果没有找到“下一页”按钮,退出循环
print("没有找到'下一页'按钮,停止执行。")
break
result=pd.concat(dfs)
# result.to_excel("Documents/PycharmProjects/invest/crawlData/all_stocks_totalvalue20241126.xlsx")
result.to_excel("all_stocks_totalvalue20250418.xlsx")
browser.quit()
# print(result)
craw the circulation market value
from selenium import webdriver
import time
import pandas as pd
from selenium.common.exceptions import NoSuchElementException
#参考地址:https://www.bilibili.com/video/BV16S4y1T7DV/?spm_id_from=333.999.0.0&vd_source=731ffa0519e33405606132cc5afc0ae0
# driver_path = 'C:\\Program Files (x86)\\Google\\Chrome\\Applicationchromedriver.exe' # 替换为你的chromedriver实际路径
browser=webdriver.Chrome()
#请求原始网页
# browser.get('https://quote.eastmoney.com/center/gridlist.html#hs_a_board') #市盈率
browser.get('https://quote.eastmoney.com/center/gridlist.html#hs_a_board') #流通市值
time.sleep(3) # 程序在这里暂停3秒,等待加载完成
#找到对应的菜单位置进行点击--市净率
# 2025.01.20 网站更新了xpath地址 browser.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[3]/ul/li[1]/a').click()
# 2025.01.20 网站更新了xpath地址
# browser.find_element_by_xpath('/html/body/div[1]/div[7]/div[2]/div/div/div[2]/ul/li[2]/a').click()#choose circulation
# time.sleep(3) # 程序在这里暂停3秒,等待加载完成
#选择总市值。
# 2025.01.20 网站更新了xpath地址 browser.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[4]/div[3]/select/option[2]').click()
# 2025.01.20 网站更新了xpath地址
browser.find_element_by_xpath('/html/body/div[1]/div[7]/div[2]/div/div/div[3]/div[2]/div/select/option[3]').click()
time.sleep(5) # 程序在这里暂停3秒,等待加载完成
#定义空列表,存储对应的数据列表数据
dfs=[]
# 循环直到没有“下一页”按钮
while True:
time.sleep(3) # 等待页面加载
data = browser.page_source # 保存网页源文件数据
df = pd.read_html(data)[1] # 假设你需要的表格是第2个表格
dfs.append(df) # 当前页面数据添加到列表中
try:
# 尝试找到“>”按钮并点击
next_page_button = browser.find_element_by_link_text(">")
next_page_button.click()
except NoSuchElementException:
# 如果没有找到“下一页”按钮,退出循环
print("没有找到'下一页'按钮,停止执行。")
break
result=pd.concat(dfs)
# result.to_excel("Documents/PycharmProjects/invest/crawlData/all_stocks_totalvalue20241126.xlsx")
result.to_excel("circulation20250418.xlsx")
browser.quit()
# print(result)
2025.05.06 更新爬取 公司产品 控股股东等信息
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.chrome.options import Options
import pandas as pd
import time
# 配置反反爬参数
chrome_options = Options()
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option("useAutomationExtension", False)
# 初始化浏览器
# browser = webdriver.Chrome()
driver = webdriver.Chrome(options=chrome_options)
wait = WebDriverWait(driver, 20)
url_template = "https://basic.10jqka.com.cn/{code}/company.html#stockpage"
all_data = []
# 定义股票代码列表
stock_codes = ['002558', '002559', '002560', '002561']
# 循环生成链接
for code in stock_codes:
# 存储数据的字典
company_data = {
'股票代码': code,
'公司名称': '',
'所属地域': '',
'所属申万行业': '',
'产品名称': [],
'控股股东': '',
'实际控制人': '',
'最终控制人': '',
'董事长': '',
'成立日期': '',
'上市日期': '',
'首日开盘价': '',
}
try:
# 访问公司详情页
# driver.get('https://basic.10jqka.com.cn/002558/company.html#stockpage')
# 替换模板中的变量
target_url = url_template.format(code=code)
driver.get(target_url)
# 显式等待公司名称加载
time.sleep(10) # 20秒超时
# inspect_page(driver)
#the company name
company_data['公司名称'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/table/tbody/tr[1]/td[2]/span').text
company_data['所属地域'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/table/tbody/tr[1]/td[3]/span').text
company_data['所属申万行业'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/table/tbody/tr[2]/td[2]/span').text
# # 提取公司基本信息表格
company_data['成立日期'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[3]/div[2]/table/tbody/tr[1]/td[1]/span').text
company_data['上市日期'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[3]/div[2]/table/tbody/tr[2]/td[1]/span').text
company_data['首日开盘价'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[3]/div[2]/table/tbody/tr[3]/td[1]/span').text
# # # 提取股东信息
company_data['控股股东'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/div/table/tbody/tr[3]/td').text
company_data['实际控制人'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/div/table/tbody/tr[4]/td').text
company_data['最终控制人'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/div/table/tbody/tr[5]/td').text
company_data['董事长'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/div/table/tbody/tr[6]/td[1]/span/a').text
# # # 提取股东信息
# company_data['控股股东'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/div/table/tbody/tr[3]/td/div/span').text
# company_data['实际控制人'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/div/table/tbody/tr[4]/td/div/span').text
# company_data['最终控制人'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/div/table/tbody/tr[5]/td/div/span').text
# company_data['董事长'] = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/div/table/tbody/tr[6]/td[1]/span/a').text
# # 提取产品信息(假设在业务概况中)
company_data['产品名称']=driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[2]/div/table/tbody/tr[2]/td/span/span').text
except Exception as e:
print(code,f"抓取过程中发生错误: {str(e)}")
continue # 跳过本次循环
finally:
all_data.append(company_data)
# # 转换数据为DataFrame并保存
# df.to_excel('company_details.xlsx', index=False)
# 转换数据为DataFrame并保存
df = pd.DataFrame(all_data)
df.to_excel('company_details20250505.xlsx', index=False)
driver.quit()
print(df)
# print("数据已保存到 company_details.xlsx")