首页 > 解决方案 > 在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))

标签: python-2.7web-scraping

解决方案


您可以使用一些简单的正则表达式轻松地做到这一点:

import re
CLEAN_TEXT = re.sub('<[^<]+?>', '', YOUR_TEXT)

享受!


推荐阅读