python - 使用 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&search_keyword=ABC">ABC</a>
但我只想得到ABC
我该如何解决这个问题?
解决方案
试试这个
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)
推荐阅读
- python - 如何删除列表框中的多个选定项目 - 使用 Python Tkinter
- c# - 分配 Task 内部的元组
- symfony - Symfony5 表单:如何默认禁用所有字段的“必填”?
- javascript - 渲染 ES6 组件在 codepen 中不起作用
- android - Android SimpleXml Parser 数据解析器错误
- python - 如何在没有 ord() 的情况下在 python 中将字符更改为 ASCII
- python - 熊猫数据框:熊猫索引get_loc的正确用法是什么?
- flask - 如何在flask_socketio和socket io中的html上连续显示数据
- reactjs - React-Router / Webpack 的问题:无法获取带有 url 参数的页面
- perl - 在 perl 中替换文本中的一组单词的速度 -