gpt4 book ai didi

python - 当代码命中缺失值时如何修复 Web 抓取 Python 代码 "IndexError: list index out of range"

转载 作者:太空宇宙 更新时间:2023-11-03 20:26:28 25 4
gpt4 key购买 nike

我正在编写网页抓取代码。该代码适用于第一页和后续页面,但是当出现不同的容器时会遇到问题。问题是,对于大多数容器,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()

最佳答案

使用 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)

关于python - 当代码命中缺失值时如何修复 Web 抓取 Python 代码 "IndexError: list index out of range",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57779146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com