【问题标题】:Python, extract text from webpagePython,从网页中提取文本
【发布时间】:2020-09-03 19:30:49
【问题描述】:

我正在做一个项目,我正在爬取数千个网站以提取文本数据,最终用例是自然语言处理。

编辑 * 因为我正在抓取 100 多个网站,所以我无法为每个网站定制抓取代码,这意味着我无法搜索特定的元素 id,我正在寻找的解决方案是通用的 *

我知道诸如美丽汤中的 .get_text() 函数之类的解决方案。这种方法的问题在于它从网站获取所有文本,其中大部分与该特定页面上的主题无关。在大多数情况下,网站页面将专注于一个主题,但在侧面、顶部和底部可能会有关于其他主题或促销或其他内容的链接或文本。

使用 .get_text() 函数,它可以一次性返回站点页面上的所有文本。问题在于它将所有内容(相关部分与不相关部分)结合在一起。是否有另一个类似于 .get_text() 的函数返回所有文本但作为列表并且每个列表对象都是文本的特定部分,这样它可以知道新科目的开始和结束。

作为奖励,有没有办法识别网页上的正文?

【问题讨论】:

  • 也许您可以尝试使用正则表达式来获取您需要的链接。
  • @MustardTiger,你试过使用find_all,它允许通过标签和属性搜索元素然后调用text

标签: python html parsing web-scraping web-crawler


【解决方案1】:

下面我提到了可以使用 BeautifulSoup4 和 Python3 以所需方式查询数据的 sn-ps:

import requests
from bs4 import BeautifulSoup

response = requests.get('https://yoursite/page')
soup = BeautifulSoup(response.text, 'html.parser')
# Print the body content in list form
print(soup.body.contents[0])
# Print the first found div on html page
print(soup.find('div'))
# Print the all divs on html page in list form
print(soup.find_all('div'))
# Print the element with 'required_element_id' id
print(soup.find(id='required_element_id'))
# Print the all html elements in list form that matches the selectors
print(soup.select(required_css_selectors))
# Print the attribute value in list form
print(soup.find(id='someid').get("attribute-name"))
# You can also break your one large query into multiple queries
parent = soup.find(id='someid')
# getText() return the text between opening and closing tag
print(parent.select(".some-class")[0].getText())

对于您更高级的要求,您也可以查看Scrapy。如果您在实现此功能时遇到任何挑战,或者您的要求是什么,请告诉我。

【讨论】:

  • 您好,我对问题进行了编辑以使事情更清楚
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多