Skip to main content
 首页 » 编程设计

python之BeautifulSoup之拼写错误的类

2024年10月17日6exmyth

我正在尝试从 https://www.wellstar.org/locations/pages/default.aspx 中抓取位置数据当我检查来源时,我注意到医院地址的类别有时会拼写一个额外的“d”——“地址”与“地址”。有没有办法在以下代码中解释这种差异?我试图合并一个 if 语句来测试 address 对象的长度,但我只得到与“address”类关联的地址。我觉得我很接近但没有想法。

import urllib 
import urllib.request 
from bs4 import BeautifulSoup 
import re 
 
def make_soup(url): 
    thepage = urllib.request.urlopen(url) 
    soupdata = BeautifulSoup(thepage,"html.parser") 
    return soupdata 
 
soup = make_soup("https://www.wellstar.org/locations/pages/default.aspx") 
 
for table in soup.findAll("table",class_="s4-wpTopTable"): 
    for type in table.findAll("h3"): 
        type = type.get_text() 
    for name in table.findAll("div",class_="PurpleBackgroundHeading"): 
        name = name.get_text() 
    address="" 
    for address in table.findAll("div",class_="WS_Location_Adddress"): 
            address = address.get_text(separator=" ") 
    if len(address)==0: 
        for address in table.findAll("div",class_="WS_Location_Address"): 
            address = address.get_text(separator = " ") 
            print(type, name, address) 

请您参考如下方法:

BeautifulSoup 很擅长适配,可以使用正则表达式:

for address in table.find_all("div", class_=re.compile(r"WS_Location_Ad{2,}ress")): 

其中 d{2,} 将匹配 d 2 次或更多次。


或者,您可以只指定类的列表:

for address in table.find_all("div", class_=["WS_Location_Address", "WS_Location_Adddress"]):