python-2.7 - 在Python(2.7)中进行网页抓取时如何选择没有html代码的文本?
问题描述
下面的代码返回包含 html 代码的文本。但是,我只需要检索文本,以便它可以很好地加载到 pd.DataFrame 中。我如何“剥离”文本?
#importing packages
from bs4 import BeautifulSoup
import requests
#url
url = "https://example.com/this_is_just_an_example"
#request to get text from url
r = requests.get(url).text
#create soup version of the text
soup = BeautifulSoup(r, features="lxml")
#create a list to store the text
MyHeadlines= []
#appended the text to list Names
for i in soup.find_all('h3', {'class': 'headline'}):
MyHeadlines.append(str(i))
解决方案
您可以使用一些简单的正则表达式轻松地做到这一点:
import re
CLEAN_TEXT = re.sub('<[^<]+?>', '', YOUR_TEXT)
享受!
推荐阅读
- selenium - selenium.WebDriverException:无法访问 chrome
- vue.js - Vuex 未捕获类型错误:无法读取 .vue 和 .js 文件中未定义的属性“提交”
- reactjs - 处理路由时如何绕过@@init?
- magento - Magento 2.4.1 付款方式未显示在管理区域
- reactjs - 重新渲染反应中的道具变化不起作用
- java - 从 json java jsonpath 通过 id 获取自定义对象
- mysql - MySQL:触发器中的Where子句,不为空的列=列或为空
- python - 使用 vosk api 和 PyInstaller 编译文件
- javascript - 将 PHP 站点的 iframe 记录到文件的位置
- reactjs - 单击reactjs中的addbtn时如何清除textarea的值?