首页 > 解决方案 > 使用 BeautifulSoup 解析 HTML,select()

问题描述

我正在尝试使用 BeautifulSoup 获取最新的帖子内容。
有时标签在最近的帖子中,有时不是。
如果标签在那里,我想获取标签,如果不存在,就获取其他文本。
我的代码如下。

import requests
from bs4 import BeautifulSoup

headers = 'User-Agent':'Mozilla/5.0'
url = "https:// " 
req = requests.get(url, headers=headers)
html = req.text       
soup = BeautifulSoup(html, 'html.parser')                
link = soup.select('#flagList > div.clear.ab-webzine > div > a')       
title = soup.select('#flagList > div.clear.ab-webzine > div > div.wz-item-header > a > span')         
latest_link = link[0] # link of latest post    
latest_title = title[0].text # title of latest post

# to get the text of latest post
t_url = latest_link
t_req = requests.get(t_url, headers=headers)
t_html = c_res.text
t_soup = BeautifulSoup(t_html, 'html.parser')  
maintext = t_soup.select ('#flagArticle > div.rhymix_content.xe_content')
tag = t_soup.select_one('div.rd.clear > div.rd_body.clear > ul > li > a').get_text()

print(maintext)
print(tag)

问题是,如果最近的帖子中没有标签,它会返回错误,如下所示。
AttributeError: 'NoneType' object has no attribute 'get_text'

如果我从该代码中删除.get_text()并且标签不在最近的帖子中,它会返回None
如果标签存在,它会返回<a href="/posts?search_target=tag&amp;search_keyword=ABC">ABC</a>
但我只想得到ABC

我该如何解决这个问题?

标签: pythonbeautifulsoup

解决方案


试试这个

import requests
from bs4 import BeautifulSoup

headers = 'User-Agent':'Mozilla/5.0'
url = "https:// " 
req = requests.get(url, headers=headers)
html = req.text       
soup = BeautifulSoup(html, 'html.parser')                
link = soup.select('#flagList > div.clear.ab-webzine > div > a')       
title = soup.select('#flagList > div.clear.ab-webzine > div > div.wz-item-header > a > span')         
latest_link = link[0] # link of latest post    
latest_title = title[0].text # title of latest post

# to get the text of latest post
t_url = latest_link
t_req = requests.get(t_url, headers=headers)
t_html = c_res.text
t_soup = BeautifulSoup(t_html, 'html.parser')  
maintext = t_soup.select ('#flagArticle > div.rhymix_content.xe_content')
try:
    tag = t_soup.select_one('div.rd.clear > div.rd_body.clear > ul > li > a').text
    print(tag)
except:
    print("Sure the tag exists on this page??")

print(maintext)

推荐阅读