【问题标题】:Using BeautifulSoup to parse webpages – to skip 404 error pages使用 BeautifulSoup 解析网页——跳过 404 错误页面
【发布时间】:2014-06-20 07:46:04
【问题描述】:

我正在使用下面的代码来获取网站的标题。

from bs4 import BeautifulSoup
import urllib2

line_in_list = ['www.dailynews.lk','www.elpais.com','www.dailynews.co.zw']

for websites in line_in_list:
    url = "http://" + websites
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page.read())
    site_title = soup.find_all("title")
    print site_title

如果网站列表包含一个“坏”(不存在)的网站/网页,或者该网站有某种类型或错误,例如“404 页面未找到”等,脚本将中断并停止。

我可以通过什么方式让脚本忽略/跳过“坏”(不存在)和有问题的网站/网页?

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:
    line_in_list = ['www.dailynews.lk','www.elpais.com',"www.no.dede",'www.dailynews.co.zw']
    
    for websites in line_in_list:
        url = "http://" + websites
        try:
           page = urllib2.urlopen(url)
        except Exception, e:
            print e
            continue
    
        soup = BeautifulSoup(page.read())
        site_title = soup.find_all("title")
        print site_title
    
    [<title>Popular News Items | Daily News Online : Sri Lanka's National News</title>]
    [<title>EL PAÍS: el periódico global</title>]
    <urlopen error [Errno -2] Name or service not known>
    [<title>
    DailyNews - Telling it like it is
    </title>]
    

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 2023-03-10
      • 2012-10-04
      • 1970-01-01
      • 2020-02-25
      相关资源
      最近更新 更多