【问题标题】:how to collect text data from a URL link with or without ".html" in the link?如何从链接中带有或不带有“.html”的 URL 链接收集文本数据?
【发布时间】:2021-02-03 23:20:40
【问题描述】:

我正在尝试从像 https://scikit-learn.org/stable/modules/linear_model.html 这样的 URL 收集一些文本数据。

我想从html中获取以下文本数据

 1.1. Linear Models¶
 The following are a set of methods intended for regression in which the target value is 
 expected to be a linear combination of the features. In mathematical notation, if 
 is the predicted value.

我的代码:

import urllib
from bs4 import BeautifulSoup
link = "https://scikit-learn.org/stable/modules/linear_model.html"
f = urllib.request.urlopen(link)
html = f.read()
soup = BeautifulSoup(html)
print(soup.prettify()) 

如何导航到嵌入的html正文中获取上述文本数据?

另外,我需要对一些没有“.html”的链接做类似的事情,我使用相同的代码,但没有从链接返回任何文本数据。

当我打印出来时,我看不到任何文本数据

 print(soup.prettify())

返回状态是

  200

可能是什么原因?

谢谢

【问题讨论】:

  • 可以分享链接的网址吗?可能是数据是通过 JavaScript 加载的,beautifulsoup 看不到它

标签: python html url beautifulsoup


【解决方案1】:

创建BeautifulSoup 对象时,您必须指定要使用的解析器。除此之外,我还建议您使用requests 而不是urllib,但这完全是您的愿望。以下是提取所需文本的方法:

div = soup.find('div', class_ = "section") #Finds the div with class section

print(div.h1.text) #Prints the text within the first h1 tag within the div

print(div.p.text) #Prints the text within the first p tag within the div

输出:

1.1. Linear Models¶
The following are a set of methods intended for regression in which
the target value is expected to be a linear combination of the features.
In mathematical notation, if \(\hat{y}\) is the predicted
value.

这里是完整的代码:

import urllib
from bs4 import BeautifulSoup
link = "https://scikit-learn.org/stable/modules/linear_model.html"
f = urllib.request.urlopen(link)
html = f.read()
soup = BeautifulSoup(html,'html5lib')

div = soup.find('div', class_ = "section")

print(div.h1.text)

print(div.p.text)

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 2011-08-02
    • 2012-09-11
    • 2012-07-06
    • 1970-01-01
    • 2013-03-01
    • 2011-02-10
    相关资源
    最近更新 更多