【问题标题】:Python & BS4: Start searching for term starting at certain divPython & BS4:开始搜索从某个 div 开始的词
【发布时间】:2014-11-23 23:55:15
【问题描述】:

Python 2.7.6 + BeautifulSoup 4 + 在这里请求新手。

我的问题涉及搜索 div 类的内容,例如 on this site。 当每列包含信息时,我只想使用一行的内容。 我能够编写一段代码来提取燃料价格的 div 类的内容(在网站上是第 1 列)。有时,最先列出的加油站已关闭,没有价格出现。所以我的代码会抓取第一个实际包含价格的 div。

pricediv = soup.find("div", {"class": "price"})
price = pricediv.text

接下来,我想获取我从中提取价格的加油站的名称和地址,它们包含在另外两个 div 类中。我该怎么做

location = soup.find("div", {"class": "location_name"})

从包含我之前提取的gas价格的div类的位置开始搜索?否则,如果前两个加油站关闭,我的变量 pricediv 将包含第三个加油站的汽油价格。但是,如果我运行代码来查找位置(如上),它将返回第一个位置(关闭的 1 号加油站)。所以我希望它在价格 div 之后立即开始寻找位置 div。

我希望我明确了我在寻找什么,并且有人可能会给我一些提示。提前致谢!

【问题讨论】:

  • 我认为你想要的是 find_all 而不是 find,你的链接也给了我一个 501 错误
  • 感谢您的回答,@PadraicCunningham,我使用“查找”是因为我只想使用列表中的第一个(因此也是最便宜的)价格。

标签: python html python-2.7 beautifulsoup python-requests


【解决方案1】:

从您提供的链接中,您的 price div 是 priceblock div 的子级,而 price_entry_table div 又是 price_entry_table div 的子级,所以在为了找到你想要的div,你需要使用parent,它应该是这样的:

pricediv = soup.find('div', {'class': 'price'})
price = pricediv.text
# use parent.parent to get to the price_entry_table div, then find location_name
locationdiv = pricediv.parent.parent.find('div', {'class': 'location_name'})
location = locationdiv.text
print price, location

# sample result
1.379 Tankstelle Wagner/DBV Würzburg

此外,如果您需要访问所有 divs,您可能需要像 @PadraicCunningham 建议的那样使用 findAll,如下所示:

for pricediv in soup.findAll('div', {'class': 'price'}):
    price = pricediv.text
    ... do your remaining code here ...

【讨论】:

  • 非常感谢@Anzel,parent 就像一个魅力。我使用find 而不是find_all 只查找列表中的第一个(最便宜的)价格,因为find_all 将返回页面上的每个价格。再次感谢您的出色回答。
  • @LaMigra,啊,现在我明白你为什么使用find 作为第一条记录了。很高兴它有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 2021-08-26
  • 1970-01-01
  • 2022-01-21
相关资源
最近更新 更多