从DIV组中刮取特定内容时出现问题

2024-04-25 21:05:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在刮这个URL

我想把所有的餐馆都搜索一下,这样我就可以在单独的变量中得到餐馆的名称、菜系类型和营业时间,但我不知道如何迭代它们

您可以从链接中看到餐厅RESTAURANT DU CASINO IVORYLA STUB DU CASINO在同一个div div.infos-restos中,所以我要迭代h3,然后让下一个兄弟姐妹进入Type of cuisine

这是我的密码

for rests in dining_soup.select("div.infos-restos"):

        for rest in rests.select("h3"):
            print("            Rest Name: "+rest.text)
            print(rest.next_sibling.next_sibling.next_sibling.next_sibling.string)

另一个问题:):第print(rest.next_sibling.next_sibling.next_sibling.next_sibling.string)行打印完整的HTML。如何只获取文本?你知道吗


Tags: indivrestforselecth3nextprint
1条回答
网友
1楼 · 发布于 2024-04-25 21:05:27

我建议你用^{}

beautifulsoup不支持xpath
在我看来,用xpath从DOM中提取数据要简单得多

以下是您的操作方法:

from lxml import etree
import requests

url = 'http://www.accorhotels.com/gb/hotel-5548-mercure-niederbronn-hotel/restaurant.shtml'
res = requests.get(url)

tree = etree.HTML(res.content)  
rest_name_xpath = '//div[@class="infos-restos"]/div[@class="detail-resto"]/following-sibling::h3'

for item in tree.xpath(rest_name_xpath):
    print item.text

输出:

RESTAURANT DU CASINO IVORY
BAR DES MACHINES A SOUS

附言: 这个网站的html写得不好,没有合适的结构。这就是为什么xpath又长又丑的原因

相关问题 更多 >