Python - 遍历 URL、查找文本、写入新列表

Python - Loop through URLs, finding text, writing to new list

我正在尝试通过 url 的列表来查找 html 文本中的内容并将其写入新列表。我遇到的问题是,虽然我有一个 for 循环,但它只输出最后一个 url(列表“urls”中有 500 个)。我不知道如何让它迭代写入然后转到下一次迭代而不是迭代然后只写列表中的最后一个。关于如何使这项工作有任何想法吗?

for url in urls:
    try:
         page = urlopen(url)
    except:
        print("Error opening the URL")    
    soup = BeautifulSoup(page, 'html.parser')
    content = soup.find('div', {"class": "sp-m-box-section"})
    article = []
        
    for url in urls:
        article = article.append(content)   #here I am completely unsure how to handle it
print(article)

感谢任何想法。

这是否解决了您的问题?

article = []

for url in urls:
    try:
         page = urlopen(url)
    except:
        print("Error opening the URL")    
    soup = BeautifulSoup(page, 'html.parser')
    content = soup.find('div', {"class": "sp-m-box-section"})       
    article.append(content)

print(article)

这里有几个问题。

  1. 你通过声明 article=[] 在每次迭代后覆盖你的 article 列表。所以即使你追加它也总是有一个空列表。在最后一次迭代之后,它不会创建 article=[],只留下它附加的最后一个东西。
  2. 为什么要遍历 url 两次?
  3. 我更改了它以不同方式处理 try/except

基本上,尝试阅读页面。如果不是,则会引发错误并继续到下一个 url (如果无法读取 html 则处理 html 是没有意义的......另外你会在那里得到一个错误嗯)

试一试:

article = []
for url in urls:
    try:
         page = urlopen(url)
    except:
        print("Error opening the URL") 
        continue
    soup = BeautifulSoup(page, 'html.parser')
    content = soup.find('div', {"class": "sp-m-box-section"})
    article.append(content.text) # <- here I'm assuming you want the actual text/content, not the html  

print(article)