【问题标题】:learning python regex and webscraping and stuck [duplicate]学习python正则表达式和网络抓取并卡住[重复]
【发布时间】:2013-09-13 06:26:51
【问题描述】:

我正在尝试使用 python 进行网络抓取。 我正在尝试获取产品的链接(我的目标)

http://www.fastfurnishings.com/3-Piece-Reversible-Bonded-Leather-Match-Sofa-Set-i-p/bstrblm3p.htm

我正在抓取这个网址/网站

 http://www.fastfurnishings.com/SearchResults.asp?Search=3-Piece+Reversible+Bonded+Leather+Match+Sofa+Set+in+Cream

如果您进行页面查看,您会发现没有特定的 id 或标签可以帮助我确定我需要的 url,而且我也不太擅长正则表达式。到目前为止,我在 python 中有这个

import urllib
import re
product = "3-Piece Reversible Bonded Leather Match Sofa Set in Cream"
productSearchUrl = product.replace(" ","+");
myurl = "http://www.fastfurnishings.com/SearchResults.asp?Search="+productSearchUrl
print myurl
htmlfile = urllib.urlopen(myurl)
htmltext = htmlfile.read()
regex = '<td valign="top" width="33%" align="center">(.+?)</td> '
r = re.compile(regex)
print re.findall(r,htmltext)

但那不是阅读任何内容...任何帮助将不胜感激

【问题讨论】:

标签: python regex python-2.7 python-3.x


【解决方案1】:

这就是您使用 HTML 解析器(例如 BeautifulSoup)的原因:

>>> import urllib2
>>> from bs4 import BeautifulSoup as BS
>>> html = urllib2.urlopen('http://www.fastfurnishings.com/SearchResults.asp?Search=3-Piece+Reversible+Bonded+Leather+Match+Sofa+Set+in+Cream')
>>> soup = BS(html)
>>> print soup.find('td', {'valign':'top', 'width':'33%', 'align':'center'}).a['href']
http://www.fastfurnishings.com/3-Piece-Reversible-Bonded-Leather-Match-Sofa-Set-i-p/bstrblm3p.htm

看看那是多么容易;)

【讨论】:

  • 你太棒了!
  • 一个简单的问题,如果 print soup.find('td', {'valign':'top', 'width':'33%', 'align':'center'})。 a['href'] 不存在。然后它会抛出一个异常。我怎样才能避免这种情况。
  • @Autolycus 将['href'] 替换为.get('href')。如果href 不存在,它将返回None
  • 这不起作用 print soup.find('td', {'valign':'top', 'width':'33%', 'align':'center'}).get( 'href') 我做错了什么?
  • @Autolycus 你忘了.a
【解决方案2】:

您最好使用网络爬虫库,例如 ScrapyBeautifulSoup。肯定会为您节省很多痛苦,并使您在抓取信息后专注于您真正想要实现的目标。

【讨论】:

    【解决方案3】:

    不要这样做,等等。看起来你没有考虑换行:

    r = re.compile(regex, re.DOTALL)
    

    【讨论】:

      猜你喜欢
      • 2015-09-05
      • 2020-09-28
      • 2013-02-17
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多