python - 用 Beautiful Soup 解析 div 子元素

标签 python html python-3.x beautifulsoup html-parsing

我正在使用 beautiful soup 来查找和解析页面上的街道地址。 最终我想将街道地址写入 Excel 文档。

这是我正在尝试解析的页面:https://montreal.lufa.com/en/pick-up-points

相关页面在类下的同一级别列出了 div 元素。我无法解析各个行。相反,我的代码只是吐出类下的所有内容。

到目前为止我的代码:

from bs4 import BeautifulSoup
from urllib2 import urlopen
import urllib2

URL = "https://montreal.lufa.com/en/pick-up-points"
html = urllib2.urlopen(URL).read().decode('UTF-8')

soup = BeautifulSoup(html, "html5lib")

business = (soup.find('div', class_="info"))

print (business)

任何帮助将不胜感激!

最佳答案

我会执行以下操作:对于每个企业,找到开放日并获取 every previous sibling :

for business in soup.find_all('div', class_="info"):
    days = business.find("div", class_="days")

    print(" ".join(sibling.get_text(strip=True) 
                   for sibling in reversed(days.find_previous_siblings())))

打印:

1600, René-Lévesque west 1600, René-Lévesque west Montreal, Quebec H3H 1P9
555 Chabanel Street West 555 Chabanel Street West Montreal, Quebec H2N 2H8
À la Boîte à Fleurs 3266 Saint-Rose Boulevard Laval, Quebec H7P 4K8
Allez Up Centre d'escalade 1555 St-Patrick Montreal, Quebec H3K 2B7
...
YMCA Cartierville 11885 Laurentien Boulevard Montreal, Quebec H4J 2R5
Zone, Real estate Agency 200 rue St-Jean Longueuil, Quebec J4H 2X5

关于python - 用 Beautiful Soup 解析 div 子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35142984/

相关文章:

python - 从数据框中的列值返回列表

python - 如何检查列表 1 中的所有元素是否在 *相同数量* 中并且以任何顺序排列在列表 2 中?

python - 将 unicode 值(不带\u)映射到正确的解码字符串

css - div 内的 IE7 换行符弄乱了底部边距

javascript - 如何从 jquery 中的文档调用 ajaxComplete 内的函数?

jquery - 在 iPhone 中禁用数字键盘解析

python - cars.iloc[[3, 0]]、cars.iloc[[3]、[0]] 和 cars.iloc[3, 0] 之间的区别

python - pylint 1.4 上忽略多个文件

python - 使用 if 语句的 meshgrid 和用户定义函数的真值不明确

javascript - 将 Python Flask JSON 字典导入 javascript 错误