【问题标题】:Data extraction by beautifulsoup and re用beautifulsoup和re提取数据
【发布时间】:2013-06-01 10:32:16
【问题描述】:

我正在尝试从 jb hifi 中提取 spcify 信息,这就是我所做的:

from BeautifulSoup import BeautifulSoup
import urllib2
import re



url="http://www.jbhifionline.com.au/support.aspx?post=1&results=10&source=all&bnSearch=Go!&q=ipod&submit=Go"

page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
Item0=soup.findAll('td',{'class':'check_title'})[0]    
print (Item0.renderContents())

输出是:

Apple iPod Classic 160GB (Black) 
<span class="SKU">MC297ZP/A</span>

我想要的是:

Apple iPod Classic 160GB (Black)

我尝试使用 re 删除其他信息

 print(Item0.renderContents()).replace{^<span:,""} 

但是没用

所以我的问题是如何删除无用的信息并获得“Apple ipod classic 160GB(black)”

【问题讨论】:

    标签: python regex beautifulsoup


    【解决方案1】:

    不要使用.renderContents();它充其量只是一个调试工具。

    只要得到第一个孩子:

    >>> Item0.contents[0]
    u'Apple iPod Classic 160GB (Black)\xc2\xa0\r\n\t\t\t\t\t\t\t\t\t\t\t'
    >>> Item0.contents[0].strip()
    u'Apple iPod Classic 160GB (Black)\xc2'
    

    BeautifulSoup 似乎没有完全正确地猜出编码,因此不间断空格 (U+00a0) 以两个单独的字节而不是一个字节的形式出现。看来 BeautifulSoup 猜错了:

    >>> soup.originalEncoding
    'iso-8859-1'
    

    您可以使用响应标头强制编码;此服务器确实设置了字符集:

    >>> page.info().getparam('charset')
    'utf-8'
    >>> page=urllib2.urlopen(url)
    >>> soup = BeautifulSoup(page.read(), fromEncoding=page.info().getparam('charset'))
    >>> Item0=soup.findAll('td',{'class':'check_title'})[0]
    >>> Item0.contents[0].strip()
    u'Apple iPod Classic 160GB (Black)'
    

    fromEncoding 参数告诉 BeautifulSoup 使用 UTF-8 而不是拉丁语 1,现在不间断空格已正确剥离。

    【讨论】:

      猜你喜欢
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多