在webscraping URL列表时,通过“AttributeError:'NoneType'对象没有属性'text'”错误随机出现

2024-06-09 04:35:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个网址列表,我喜欢通过循环和刮他们。我的代码可以很好地为每个网址单独!但是当我在列表中循环时,它开始给我这个错误:

Traceback (most recent call last):
File "/path/x.py", line 41, in <module>
   match = soup.find('div', id="threat").text
AttributeError: 'NoneType' object has no attribute 'text' 

每次这个错误都会出现在列表中的一个随机URL中。一旦它通过错误的第三个网址,一次第二,一次第五。我检查了所有的网址单独和没有错误的代码和刮他们单独!你知道吗

知道这里发生了什么吗?你知道吗



for i in range(len(lines)):
    x = lines[i]
    source_ = requests.get(x).text
    soup = BeautifulSoup(source_, 'lxml')
    match = soup.find('div', id="threat").text
    with open('microsoftScrapped.txt', 'a') as out:
        out.write('\n' + '\n' + '\t' + '\t' + '\t' + "====== " + " #: " + str(num)  + "   " + x + " ======" + '\n' + '\n')
        out.write(match)
        print(num)
        print(x)
        num+=1

Tags: 代码textindivid列表match错误