【问题标题】:Beautiful Soup Cleaning and Errors美丽的汤清洗和错误
【发布时间】:2016-08-18 10:25:14
【问题描述】:

我有这个代码:

from bs4 import BeautifulSoup
import urllib2
from lxml import html
from lxml.etree import tostring 
trees = urllib2.urlopen('http://aviationweather.gov/adds/metars/index?                             station_ids=KJFK&std_trans=translated&chk_metars=on&hoursStr=most+recent+only&ch    k_tafs=on&submit=Submit').read()
soup = BeautifulSoup(open(trees))
print soup.get_text()
item=soup.findAll(id="info")
print item

但是,当我在窗口上输入汤时,它给了我一个错误,当我的程序运行时,它给了我一个很长的 html 代码

等等。任何帮助都会很棒。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    第一个问题在这部分:

    trees = urllib2.urlopen('http://aviationweather.gov/adds/metars/index?station_ids=KJFK&std_trans=translated&chk_metars=on&hoursStr=most+recent+only&chk_tafs=on&submit=Submit').read()
    soup = BeautifulSoup(open(trees))
    

    trees是一个类文件对象,不需要在上面调用open(),修复它:

    soup = BeautifulSoup(trees, "html.parser")
    

    我们还将html.parser 明确设置为底层解析器。


    然后,您需要具体了解要从页面中提取的内容。以下是获取METAR text 值的示例代码:

    from bs4 import BeautifulSoup
    import urllib2
    
    
    trees = urllib2.urlopen('http://aviationweather.gov/adds/metars/index?station_ids=KJFK&std_trans=translated&chk_metars=on&hoursStr=most+recent+only&chk_tafs=on&submit=Submit').read()
    soup = BeautifulSoup(trees, "html.parser")
    
    item = soup.find("strong", text="METAR text:").find_next("strong").get_text(strip=True).replace("\n", "")
    print item
    

    打印KJFK 220151Z 20016KT 10SM BKN250 24/21 A3007 RMK AO2 SLP183 T02440206

    【讨论】:

    • 谢谢@alecxe。我会做出这些改变。
    • 我在进行这些升级时遇到了问题,但现在我想使用 url 来获取 fly.faa.gov/flyfaa/flyfaaindex.jsp?ARPT=JFK&p=0 但它给了我这个错误:“AttributeError: 'NoneType' object has no attribute 'find_next'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    相关资源
    最近更新 更多