【问题标题】:Extracting text from link in python从python中的链接中提取文本
【发布时间】:2017-08-26 20:32:11
【问题描述】:

我在 python 2.7 中有一个脚本可以在这个页面中抓取表格: http://www.the-numbers.com/movie/budgets/all

我想提取每一列,问题是我的代码无法识别具有链接的列(第 2 列和第 3 列)。

budgeturl = "http://www.the-numbers.com/movie/budgets/all"
s = urllib.urlopen(budgeturl).read()
htmlpage = etree.HTML(s)
htmltable = htmlpage.xpath("//td[@class='data']/text()")

使用此代码 htmltable[0] 是排名,htmltable[1] 是生产预算并从那里继续。 从我丢失的那些中,我需要文本而不是链接。

【问题讨论】:

  • 你能不指定class='data'就直接抓取文本吗?其他 TD 好像没有类。
  • 不知道怎么做

标签: python python-2.7 web-scraping


【解决方案1】:

您需要修改 xpath,因为并非所有 td 元素都有 class="data"。 试试这个 xpath 表达式://td//text()

import urllib
from lxml import etree

budgeturl = "http://www.the-numbers.com/movie/budgets/all"
s = urllib.urlopen(budgeturl).read()
htmlpage = etree.HTML(s)
htmltable = htmlpage.xpath("//td//text()")

输出:

【讨论】:

    【解决方案2】:
    import urllib
    
    budgeturl = "http://www.the-numbers.com/movie/budgets/all"
    s = urllib.urlopen(budgeturl).read()
    
    def find_between( s, first, last ):
        try:
            start = s.index( first ) + len( first )
            end = s.index( last, start )
            return s[start:end]
        except ValueError:
            return ""
    
    s = find_between(s, '<table>', '</table>')
    
    print s[:500]
    print '.............................................................'
    print s[-250:]
    

    Find string between two substrings

    返回:

    >>>
    <tr><th>&nbsp;</th><th>Release Date</th><th>Movie</th><th>Production Budget</th><th>Domestic Gross</th><th>Worldwide Gross</th></tr>
    <tr><td class="data">1</td>
    <td><a href="/box-office-chart/daily/2009/12/18">12/18/2009</a></td>
    <td><b><a href="/movie/Avatar#tab=summary">Avatar</a></td>
    <td class="data">$425,000,000</td>
    <td class="data">$760,507,625</td>
    <td class="data">$2,783,918,982</td>
    <tr>
    <tr><td class="data">2</td>
    <td><a href="/box-office-chart/daily/2015/12/18">12/18/2015</a></td>
    .............................................................
    </td>
    <td><a href="/box-office-chart/daily/2005/08/05">8/5/2005</a></td>
    <td><b><a href="/movie/My-Date-With-Drew#tab=summary">My Date With Drew</a></td>
    <td class="data">$1,100</td>
    <td class="data">$181,041</td>
    <td class="data">$181,041</td>
    <tr>
    

    .........................................
    

    我需要文本而不是链接。

    通过http://www.convertcsv.com/html-table-to-csv.htm

    Release Date,Movie,Production Budget,Domestic Gross,Worldwide Gross
    1,12/18/2009,Avatar,"$425,000,000","$760,507,625","$2,783,918,982"
    8/5/2005,My Date With Drew,"$1,100","$181,041","$181,041"
    

    您可以使用 beautifulsoup 来做同样的事情,请参阅:

    beautifulSoup html csv

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多