【问题标题】:Scraping data from multiple links on a webpage从网页上的多个链接中抓取数据
【发布时间】:2014-01-30 01:10:30
【问题描述】:

我正在尝试从以下网站收集德克萨斯州所有城市的生活成本指数数据:http://www.city-data.com/city/Texas.html

从网页中抓取数据的最简单方法是什么?我曾尝试使用名为 Web Scraper 的 Chrome 扩展程序,但没有成功。我认为使用 XML 包或尝试使用 Scrapy 可能会更好地与 R 配合使用。我查找了两种方法,但有些迷路,正在寻找方向。任何输入都会有所帮助。

【问题讨论】:

    标签: python r web-scraping scrapy


    【解决方案1】:

    您可以使用BeautifulSoup4 (bs4) 来解析和读取 HTML-Data。 请看一下这个例子:

    In [4]: from urllib2 import urlopen
    
    In [5]: citylinkpage = urlopen("http://www.city-data.com/city/Texas.html")
    
    In [7]: from bs4 import BeautifulSoup as BS
    
    In [8]: soup = BS(citylinkpage)
    
    In [9]: allImportantLinks = soup.select('table.cityTAB td.ph a')
    
    In [10]: print allImportantLinks[:10]
    [<a href='javascript:l("Abbott");'>Abbott</a>, <a href='javascript:l("Abernathy");'>Abernathy</a>, <a href="Abilene-Texas.html">Abilene, TX</a>, <a href="Addison-Texas.html">Addison, TX</a>, <a href="Alamo-Heights-Texas.html">Alamo Heights</a>, <a href='javascript:l("Albany");'>Albany, TX</a>, <a href="Alice-Texas.html">Alice</a>, <a href="Allen-Texas.html">Allen, TX</a>, <a href='javascript:l("Alma");'>Alma, TX</a>, <a href="Alpine-Texas.html">Alpine, TX</a>]
    
    In [14]: allCityUrls = ["http://www.city-data.com/city/"+a.get('href') for a in allImportantLinks if not a.get('href').startswith('javascript:')]
    
    In [15]: allCityUrls
    Out[15]: 
    ['http://www.city-data.com/city/Abilene-Texas.html',
     'http://www.city-data.com/city/Addison-Texas.html',
     'http://www.city-data.com/city/Alamo-Heights-Texas.html',
     'http://www.city-data.com/city/Alice-Texas.html',
     'http://www.city-data.com/city/Allen-Texas.html',
     'http://www.city-data.com/city/Alpine-Texas.html',
     'http://www.city-data.com/city/Amarillo-Texas.html',
    ...
    

    因为每个城市的页面似乎是糟糕的 HTML(尤其是围绕这个索引),所以通过正则表达式搜索页面似乎更好(使用内置的 re-module)

    cityPageAdress = "http://www.city-data.com/city/Abilene-Texas.html"
    pageSourceCode = urlopen(cityPageAdress).read()
    import re
    expr = re.compile(r"cost of living index in .*?:</b>\s*(\d+(\.\d+)?)\s*<b>")
    print expr.findall(pageSourceCode)[0][0]
    Out: 83.5
    

    【讨论】:

    • #pageSourceCode = ... 在代码的第二位中指的是什么?我无法运行那段代码。
    • 有没有办法防止我运行代码时网站崩溃?我尝试使用以 400 个为一组分区的 url 列表运行代码,但它仍然崩溃。有任何想法吗? error: urllib2.URLError:
    • 感谢您的帮助。我还有一个问题。是否可以使用正则表达式提取城市的县名?
    • 这看起来像 beatifulsoup4 的例子:我寻找每个以“/county”开头的链接,取第一个并取其文本:soup.select('a[href^=/county]')[0].getText()
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 2019-06-05
      相关资源
      最近更新 更多