请问为什么列表超出索引了呀?谢谢!
import requests
import re
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67'}
ur1 = 'https://search.cs.com.cn/search?searchword=%E8%B4%B5%E5%B7%9E%E8%8C%85%E5%8F%B0&channelid=215308'
res = requests.get(ur1, headers=headers).text
p_title = 'href=".*?" target="_blank">(.*?)</a>'
p_href = 'href="(.*?)" target="_blank">.*?</a>'
p_date = ' (.*?)</td></tr>'
title = re.findall(p_title, res)
href = re.findall(p_href, res)
date = re.findall(p_date, res)
source = []
for i in range(len(title)):
source.append('中国证券报')
date[i] = date[i].strip()
date[i] = re.sub('.','-',date[i])
date[i] = date[i].split(' ')[0]
print(str(i+1) + '.' + title[i] + '(' + source[i] + ' ' +date[i] + ')')
print(href[i])
问题点: 列表超出索引
分析思路: 分别(打印)输出title和date的长度, 结果分别为20和0。这说明抓取的date信息为空列表.
【以下回答由 GPT 生成】
问题原因是网页的内容并没有与正则表达式的匹配项一一对应。在这种情况下,使用提取数据时的索引就会超出列表的范围,导致超出索引的错误。
解决方案:
确保网页的内容与正则表达式的匹配项一一对应。可以通过检查网页源代码和正则表达式来确保它们之间的匹配关系。
在提取数据之前,先检查列表的长度或匹配项的数量,避免将索引用于超出列表范围的位置。
以下是修改后的代码示例:
import requests
import re
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67'}
url = 'https://search.cs.com.cn/search?searchword=%E8%B4%B5%E5%B7%9E%E8%8C%85%E5%8F%B0&channelid=215308'
response = requests.get(url, headers=headers)
content = response.text
p_title = 'href="(.*?)" target="_blank">(.*?)</a>'
p_href = 'href="(.*?)" target="_blank">.*?</a>'
p_date = ' (.*?)</td></tr>'
titles = re.findall(p_title, content)
hrefs = re.findall(p_href, content)
dates = re.findall(p_date, content)
sources = []
length = min(len(titles), len(hrefs), len(dates)) # 检查列表的最小长度
for i in range(length):
sources.append('中国证券报')
dates[i] = dates[i].strip()
dates[i] = re.sub('\.', '-', dates[i])
dates[i] = dates[i].split(' ')[0]
print(str(i+1) + '.' + titles[i] + '(' + sources[i] + ' ' + dates[i] + ')')
print(hrefs[i])
在修改后的代码中,我们通过使用min()
函数来获取列表的最小长度,以确保索引不会超出范围。只有当所有的列表都有相同的长度时,才会进行数据的提取和打印操作。这样可以避免超出索引的问题。
【相关推荐】