【问题标题】:Webscraping with BeautifulSoup in Python在 Python 中使用 BeautifulSoup 进行网页抓取
【发布时间】:2017-02-24 16:02:38
【问题描述】:
resp = urlopen('http://international.o2.co.uk/internationaltariffs 
/getintlcallcosts?countryId=IND').read()
crawler = bs4.BeautifulSoup(resp, 'html.parser')
div = crawler.find('div', {"id": "standardRates"})
div

使用上面的代码,它列出了您可以在图像中看到的所有标签/元素。我想得到“2.00 英镑”。除非我再次调用 .find('td') 如下:

div = crawler.find('div', {"id": "standardRates"}).find('td')

它只返回 Landline 而不是下面的行,即使它具有相同的标签。我在网络抓取方面的经验很少。我如何定位这个标签(2.00 英镑的行)?

【问题讨论】:

  • 试试findAll() 而不是find()
  • .findAll('td')[1] 准确地说
  • 效果很好。虽然结果是一个列表,所以当我使用 .contents 时,字符串被方括号括起来。我可以得到它,所以它只是一个字符串?
  • 这是现在的代码行: div = crawler.find('div', {"id": "standardRates"}).findAll('td')[1].contents 和它返回 ['£2.00']
  • 我只是使用 .join 它不是那么优雅,但可以完成工作。感谢您的有用回复!

标签: python web-scraping beautifulsoup


【解决方案1】:

您可以使用这种方法直接找到上一个 2.00 英镑的兄弟姐妹。

首先找到所需的表,然后找到tdLandline 作为字符串。然后得到这个td的父级,得到这个的下一个兄弟,最后得到下一个兄弟。

>>> import requests
>>> get = requests.get('http://international.o2.co.uk/internationaltariffs/getintlcallcosts?countryId=IND')
>>> page = get.text
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(page,'lxml')
>>> Landline_td = soup.find('table', {'id': 'standardRatesTable'}).find_all(string='Landline')[0]
>>> Landline_td
'Landline'
>>> Landline_td.findParent().findNextSibling()
<td>£2.00</td>
>>> Landline_td.findParent().findNextSibling().text
'£2.00'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 2020-10-04
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    相关资源
    最近更新 更多