首页 > 解决方案 > 从多个网站提取文本

问题描述

from bs4 import BeautifulSoup
import re
import urllib2
import urllib
list_open = open("weblist.txt")
read_list = list_open.read()
line_in_list = read_list.split("\n")
for url in line_in_list:
        Beautiful = urllib2.urlopen(url).read()
        beautiful
        soup = bs4.BeautifulSoup(beautiful)
        for news in soup:
                 print soup.getText()

以下代码帮助我从多个网站(weblist.txt)中提取文本

但是当我的网络列表包含任何不使用此代码打开的链接或网站时,它会立即停止并且不检查进一步的链接。假设如果我有 10 个链接,而第二个链接未打开或无法解析,它会给出错误并在该链接中停止而不检查进一步的链接。我希望它应该检查 weblist 中的每个链接(从开始到结束)并从中提取文本所有那些真实的或能够解析的链接。

标签: pythonweb-scrapingweb-crawler

解决方案


只需添加一个 try except 语句,如下所示:

for url in line_in_list:
    try:
        Beautiful = urllib2.urlopen(url).read()
        beautiful
        soup = bs4.BeautifulSoup(beautiful)
        for news in soup:
             print soup.getText()
    except Exception as e:
        #Error handling
        print(e)

推荐阅读