这是网站找到爬虫程序,主要任务是爬虫巨潮网上市公司及评级信息,
https://blog.csdn.net/c1007857613/article/details/130243238?ops_request_misc
import pandas as pd
from selenium import webdriver
import time
import re
import datetime
import warnings
warnings.filterwarnings("ignore")
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome = webdriver.Chrome(options=chrome_options)
start_date = datetime.datetime.now()
end_date = start_date - datetime.timedelta(days=90)
end_date = end_date.strftime('%Y-%m-%d')
url = 'http://data.eastmoney.com/report/stock.jshtml'
chrome.get(url)
content = chrome.page_source
#总页码和下一页按钮的xpath:即在网页html中的位置
total_xpath = '//*[@id="stock_table_pager"]/div[1]/a[7]'
next_xpath = '//*[@id="stock_table_pager"]/div[1]/a[last()]'
#找到总页码并解析到总页码
total_page = chrome.find_element_by_xpath(total_xpath).text
page = 0
data_all = pd.DataFrame()
while(True): #循环多页爬取
content = chrome.page_source
# print(content)
#因为网页上的数据是一个表格,可使用read_html方法直接解析表格
tables = pd.read_html(content)
print(len(tables))
print(tables)
table = tables[1] #我们要的数据在第二个表格中
if end_date in table['日期'].values: #如果数据中的日期在我们设定的截止日期之前就不要了
break
#股票代码可能以0开头,而read_html解析出来的股票代码自动把0去掉了,因此需要从新解析股票代码
#使用正则解析股票代码
p_code = '<a href="//quote.eastmoney.com/unify/.*?">(.*?)</a>'
code = re.findall(p_code, content)
table['股票代码'] = code
#每一页解析的数据拼接在一起
data_all = pd.concat([data_all,table],ignore_index=True)
print('第' + str(page + 1) + '页爬取完成!')
#翻页,继续爬取解析下一页的数据
chrome.find_element_by_xpath(next_xpath).click()
page = page + 1
time.sleep(3)
#限定只需要某些列的数据
columns = ['股票代码','股票简称','东财评级','评级变动','机构','日期']
data_all = data_all[columns]
#将数据写入到excel文件中去
data_all.to_excel('eastmoney.xlsx',index='index')
执行以下程序报错如下:
line 39, in <module>
table = tables[1] #我们要的数据在第二个表格中
~~~~~~^^^
IndexError: list index out of range
通网页元素查询,应该有两个表格,但是错误现实不能识别第二个表格;


从网站上看是1个表格,但是从元素上是两个表格。请问大家这个程序应该如何修正程序解决这个问题。