Python2.7.6+ BeautifulSoup 4+在这里请求noob。
我的问题是搜索div类的内容,比如在这个网站上。我只想在每一列包含信息时使用行的内容。我编写了一段代码,提取燃料价格的div类的内容(在网站上是第1列)。有时,首先上市的加油站被关闭,没有价格出现。所以我的代码获得了包含价格的第一个div。
pricediv = soup.find("div", {"class": "price"})
price = pricediv.text接下来,我想获取我提取的加油站的名称和地址,这些价格包含在另外两个div类中。我怎么才能
location = soup.find("div", {"class": "location_name"})开始寻找包含我之前提取的汽油价格的div级的位置?否则,如果前两个加油站关闭,我的可变价格将包含第三个加油站的汽油价格。但是,如果我运行代码来查找位置(如上面所示),它将返回第一个位置(关闭的第一个加油站)。所以我想让它开始寻找价格之后的位置。
我希望我说清楚了我在寻找什么,有人可能会给我一个提示。提前感谢!
发布于 2014-11-24 00:35:11
从您提供的链接来看,您的 div是priceblock 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此外,如果您需要访问所有div,您可能希望使用findAll like @PadraicCunningham,如下所示:
for pricediv in soup.findAll('div', {'class': 'price'}):
price = pricediv.text
... do your remaining code here ...https://stackoverflow.com/questions/27095927
复制相似问题