【问题标题】:Scraping from webpage - python从网页抓取 - python
【发布时间】:2014-10-30 18:48:59
【问题描述】:

我对使用 python 进行网络编程非常陌生。目前,我正在研究从网站“抓取”一小段信息。 网址:http://www.airport-data.com/airport/HJO/#location 要提取/报废的信息:“海拔”(参见位置和速览)

我目前的代码:

from BeautifulSoup import BeautifulSoup
url2 = urllib2.urlopen('http://www.airport-data.com/airport/HJO/#location').read()
soup = BeautifulSoup(url2)
print soup #I did this just to see the content.

我尝试在线阅读并查看了一些以前的帖子,但未能完全理解。关于如何从网络链接中提取/抓取“海拔”的任何建议? 谢谢

【问题讨论】:

    标签: python python-2.7 web-scraping html-parsing beautifulsoup


    【解决方案1】:

    首先,根据BeautifulSoup project documentation

    美汤3已被美汤4取代。

    Beautiful Soup 3 仅适用于 Python 2.x,但 Beautiful Soup 4 也适用 适用于 Python 3.x。 Beautiful Soup 4 速度更快,功能更多, 并与 lxml 和 html5lib 等第三方解析器一起使用。你应该 为所有新项目使用 Beautiful Soup 4。

    安装BeautifulSoup 4-th version:

    pip install beautifulSoup4 
    

    然后,想法是找到包含Elevation:文本的标签并获取the next sibling

    import urllib2
    from bs4 import BeautifulSoup
    
    url2 = urllib2.urlopen('http://www.airport-data.com/airport/HJO/#location')
    soup = BeautifulSoup(url2)
    
    print soup.find('td', class_='tc1', text='Elevation:').next_sibling.text
    

    打印:

    240 ft / 73.15 m (Estimated)
    

    【讨论】:

    • 感谢您的回答。我做了soup.find('td', class_='tc0', text='Longitude/Latitude:').next_sibling.text,它正在提取内容。但是'Longitude/Latitude:' 有两行由<br> 分隔,我如何仅提取第二行,即<br> 之后的内容? (我可以通过字符串操作获得第二行,但想知道是否可以在没有字符串操作的情况下提取)
    • @SrinGupta 当然,print soup.find('td', text='Longitude/Latitude:').next_sibling.contents[2] 应该这样做。
    猜你喜欢
    • 2019-06-25
    • 1970-01-01
    • 2021-01-12
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    相关资源
    最近更新 更多