找到列表中的项目,但当我按索引询问位置时,它说找不到该项目

Item in list found but when I ask for location by index it says that the item can't be found

我正在编写一些代码来为数据库获取佛罗里达州某些县的列表。这些县列在一个网站上,但每个县都在单独的网页上。为了使收集过程不那么乏味,我正在编写一个网络爬虫。我已经获得了各县所有网站的链接。我编写了代码,然后检查网站,找到写着“COUNTY:”的行,然后我想获取位置,这样我就可以在下一行实际获取县。唯一的问题是当我询问它说找不到的位置时。我知道它在那里,因为当我要求我的代码找到它然后 return 行(不是位置)时它不会 return 为空。我会给出一些参考代码和问题图片。

损坏的代码:

links = ['https://www.ghosttowns.com/states/fl/acron.html', 'https://www.ghosttowns.com/states/fl/acton.html']
import requests
r = requests.get(links[1])
r = str(r.text)
r = r.split("\n")
county_before_location = [x for x in r if 'COUNTY' in x]
print(county_before_location)
print(r.index(county_before_location))

Returns:

['    </font><b><font color="#80ff80">COUNTY:</font><font color="#ffffff">'] is not in list

显示项目的代码:

links = ['https://www.ghosttowns.com/states/fl/acron.html', 'https://www.ghosttowns.com/states/fl/acton.html']
import requests
r = requests.get(links[1])
r = str(r.text)
r = r.split("\n")
county_before_location = [x for x in r if 'COUNTY' in x]
print(county_before_location)

Returns:

['    </font><b><font color="#80ff80">COUNTY:</font><font color="#ffffff">']

Photo

county_before_location 是一个列表,您要的是该列表的索引,它不在 r 中。相反,您需要请求 r.index(county_before_location[0]).