Skip to main content
 首页 » 编程设计

python之在 Beautifulsoup 中使用 select 函数返回 None 值

2025年05月04日11java哥

我正在使用 Python-2.7 和 BeautifulSoup

引用我的this问题 我正在尝试从名称几乎相似的 div 标签中获取内容。因此我要求严格检查div标签的类名。

以下是我的代码-

list = ['Link1','Link2','Link3','Link4',....etc] 
for i in list: 
    mech = Browser() 
    mech.set_handle_robots(False) 
    mech.set_handle_equiv(False) 
    hadr = {'User-Agent':'Agent'} 
    req = urllib2.Request(i,headers=hadr) 
    try: 
            pan = urllib2.urlopen(req) 
            soup = BeautifulSoup(pan, "lxml")  
            tag1 = soup.select("div[class=profile-container abc-profile-container]") 
            print "TAG_1",tag1 
            tag2 = soup.select("div[class=profile-container]") 
            print "TAG_2",tag2 
    except Exception as e: 
            print e 
            print(type(e)) 

此外,我想说明的是,列表中的任何随机链接都包含 tag1 的 div 类,但其输出为空白。

所有我想要的链接 ("div[class=profile-container abc-profile-container]") 应该接受 tag1 并相应地工作,而不是给出一个空白列表作为输出。

请您参考如下方法:

使用CSS Selectors在 .select()

中
tag1 = soup.select("div.profile-container.abc-profile-container") 
tag2 = soup.select("div.profile-container")