![](/img/trans.png)
[英]How to fix Python “IndexError: list index out of range” with CNN code
[英]How to fix web scraping Python code “IndexError: list index out of range” when the code hits missing values
我正在研究网络抓取代码。 该代码在第一页和随后的页面上均能很好地工作,但是当出现另一个容器时会遇到问题。 问题是,对于大多数容器,class =“ date”包含两个变量(用户[0]和日期[1]的条目数),但是,当匿名用户发帖时,它仅显示日期[0] 。 由于该代码旨在查找第二个条目,因此由于“ IndexError:列表索引超出范围”而在此处停止
我曾尝试创建一个if循环,但是自从我是一个初学者以来,它就没有用。 有什么办法可以解决这个问题?
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
from random import randint
from time import sleep
from requests import get
out_filename = "Repromeda.csv"
headers = "text,user_name,date \n"
f = open(out_filename, "w")
f.write(headers)
pages = [str(i) for i in range(1,20)]
for page in pages:
response = get('https://www.emimino.cz/diskuse/1ivf-repromeda-56566/strankovani/'+ page)
sleep(randint(5,10))
#opening up connection, grabing the page
page_soup = soup(response.text, 'html.parser')
#grabs each container
containers = page_soup.findAll("div",{"class":"discussion_post"})
for container in containers:
text1 = container.div.p
text = text1.text.replace('\n', ' ')
user_container = container.div.b
user_id = user_container.text
date_container = container.findAll("span",{"class":"date"})
date = date_container[1].text
print("text: " + text + "\n" )
print("user_id: " + user_id + "\n")
print("date: " + date + "\n")
# writes the dataset to file
f.write(text.replace(",", "|") + ", " + user_id + ", " + date + "\n")
f.close()
由于该代码旨在查找第二个条目,因此由于“ IndexError:列表索引超出范围”而在此处停止,我尝试创建一个if循环,但是由于我是初学者,因此无法正常工作。
您是否仅在捕获date[1]
时才尝试捕获它? 在这种情况下,您可以在一个简单的try-catch块中简化查询:
try:
date = date_container[1].text
except IndexError:
date = "Not Available"
由于即使用户是匿名用户,日期仍然可用,因此您仍然可以使用except子句捕获日期。
try:
date = date_container[1].text
except IndexError:
date = date_container[0].text
使用bs4 4.7.1 +(不了解早期版本),您可以访问:last-child
伪选择器。 您可以使用它来确保始终获得容器中具有类date
的最后一个元素(而不必担心索引)
for container in containers:
text1 = container.div.p
text = text1.text.replace('\n', ' ')
user_container = container.div.b
user_id = user_container.text
date = container.select_one('.date:last-child').text
print("text: " + text + "\n" )
print("user_id: " + user_id + "\n")
print("date: " + date)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.