我正在尝试使用 beautifulsoup 和 python 从网页中提取信息。我想提取特定标签下方的信息。为了知道它是否是正确的标签,我想对其文本进行比较,然后在下一个直接标签中提取文本。
举例来说,如果以下内容是 HTML 页面源代码的一部分,
<div class="row">
::before
<div class="four columns">
<p class="title">Procurement type</p>
<p class="data strong">Services</p>
</div>
<div class="four columns">
<p class="title">Reference</p>
<p class="data strong">ANAJSKJD23423-Commission</p>
</div>
<div class="four columns">
<p class="title">Funding Agency</p>
<p class="data strong">Health Commission</p>
</div>
::after
</div>
<div class="row">
::before
::after
</div>
<hr>
<div class="row">
::before
<div class="twelve columns">
<p class="title">Countries</p>
<p class="data strong">
<span class>Belgium</span>
", "
<span class>France</span>
", "
<span class>Luxembourg</span>
</p>
<p></p>
</div>
::after
</div>
Run Code Online (Sandbox Code Playgroud)
我想检查是否<p class="title">具有文本值,Procurement …
使用 BeautifulSoup 的 prettify 后,我想删除周围的换行符和缩进span,也许还有其他内联标签。
例如,我目前有这样的东西:
>>> import bs4
>>> html = "<div><p>I don't want this <span>span element</span> on it's one line.</p></div>"
>>> soup = bs4.BeautifulSoup(html, "html.parser")
>>> soup.prettify()
"<div>\n <p>\n I don't want this\n <span>\n span element\n </span>\n on its one line.\n </p>\n</div>"
>>> print(soup.prettify())
<div>
<p>
I don't want this
<span>
span element
</span>
on it's one line.
</p>
</div>
Run Code Online (Sandbox Code Playgroud)
我可以使用什么正则表达式来删除跨度标签周围的缩进空格和换行符,以便我最终得到以下结果:
<div>
<p>
I don't want this <span>span element</span> on its one line.
</p>
</div>
Run Code Online (Sandbox Code Playgroud) 我试图在这个 Python 脚本中深入两个级别。我看到的所有示例都使用 find_all 向下钻取单个级别,并且我可以正常工作,但我无法深入到第三级别。这是我的代码片段:
main_table = soup.find("div",attrs={'class':'block-content'})
label_item_contents = main_table.find_all("div", attrs={'class':'label-item-description'})
links = label_item_contents.find_all("a")
print(links)
Run Code Online (Sandbox Code Playgroud)
这样做会出现错误“AttributeError:ResultSet 对象没有属性‘find_all’。”
如果我注释掉并更改打印,那么就是这样:
main_table = soup.find("div",attrs={'class':'block-content'})
label_item_contents = main_table.find_all("div", attrs={'class':'label-item-description'})
print(label_item_contents)
Run Code Online (Sandbox Code Playgroud)
然后我看到所有抓取的数据。我读到问题可能是 label_item_contents 变成了一个数组,所以我尝试这样做:
links = label_item_contents[].find_all("a")
Run Code Online (Sandbox Code Playgroud)
但后来我得到“SyntaxError:无效语法”
任何帮助表示赞赏!
编辑:这是当我使用 print(label_item_contents) 时在第二个示例中返回的 HTML 的一部分:
<div class="label-item-description">
<div>
<a href="/label/example.com"><strong>Example</strong></a>
</div>
<small>
<i class="fa fa-facebook-official"></i> 342.4K
<i class="fa fa-soundcloud"></i> 233.4K
</small>
<br />
<small class="text-muted">
Stockholm, Sweden
</small>
<br />
<small class="text-muted">
<b>Techno, Tech House</b>
</small>
</div>, <div class="label-item-description">
Run Code Online (Sandbox Code Playgroud)
我只想到达<a href="/label/example.com">
@ayivima 有一个很好的答案,但我应该补充一点,该网站本身最终没有被 BeautifulSoup 正确抓取,因为它有大量的 Javascript。
所以我对使用Python完全陌生,我只是想打印网页的标题。我主要使用来自谷歌的代码:
from bs4 import BeautifulSoup, SoupStrainer
import requests
url = "https://www150.statcan.gc.ca/t1/tbl1/en/tv.action?pid=3210001601"
page = requests.get(url)
data = page.text
soup = BeautifulSoup
soup.find_all('h1')
print(text)
Run Code Online (Sandbox Code Playgroud)
我不断收到错误:
AttributeError: 'str' object has no attribute 'descendants'
Run Code Online (Sandbox Code Playgroud)
老实说,我真的不知道这意味着什么,我能找到的唯一其他答案来自:AttributeError: 'str' object has no attribute 'descendants'我认为这不适用于我?
我在代码中做错了什么吗?(可能很多,但我的意思主要是为了这个错误)
我正在尝试从ABBV 10-k sec 文件中的一个表格中提取列标题(第 25 页上的“发行人购买股权证券”表格-图表下方。)
<td>列标题标签中的内部标签<tr>,文本位于单独的<div>标签中,如下例所示
<tr>
<td>
<div>string1</div>
<div>string2</div>
<div>string3</div>
</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
当尝试从标签中提取所有文本时,文本之间没有空格分隔(例如,对于上述 html 输出将是string1string3string3预期的string1 string3 string3)。
使用下面的代码从表中提取列标题
url = 'https://www.sec.gov/Archives/edgar/data/1551152/000155115218000014/abbv-20171231x10k.htm'
htmlpage = requests.get(url)
soup = BeautifulSoup(htmlpage.text, "lxml")
table = soup.find_all('table')[76]
rows = table.find_all('tr')
table_data = []
for tr in rows[2:3]:
row_data=[]
cells = tr.find_all(['td', 'th'], recursive=False)
for cell in cells[1:4]:
row_data.append(cell.text.encode('utf-8'))
table_data.append([x.decode('utf-8').strip() for x in row_data])
print(table_data)
Run Code Online (Sandbox Code Playgroud)
输出:
[['(a) TotalNumberof Shares(or …
当我运行代码时:
import requests
from bs4 import BeautifulSoup
import urllib
response = urllib.urlopen('file:///Users/kerss/diet/sesame_seeds.html')
html = response.read()
soup = bs4.BeautifulSoup(html, 'html.parser')
span = soup.find("span", id="NUTRIENT_0")
print(span.text)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
File "c:\users\kerss\diet\scrape.py", line 8, in <module>
soup = bs4.BeautifulSoup(html, 'html.parser')
NameError: name 'bs4' is not defined
Run Code Online (Sandbox Code Playgroud)
但是bs4定义了?或不?
我正在尝试使用单个输入来抓取某个网站。现在我已经用 Scrapy 构建了它,在进行所有调整(包括不遵守 robots.txt)之后,它工作得很好,并且它自动循环运行以进行数据挖掘。
现在我需要制作一些可以通过输入抓取单个页面的东西
问题是,我能够访问的唯一页面是 robots.txt 页面,并且我无法在网上找到任何有关 robots.txt 的信息。
有没有关于如何使用 BS 或 Requests 进行操作的教程?
我正在开发一个需要从网站提取所有链接的项目,使用此代码我将从单个 URL 获取所有链接:
import requests
from bs4 import BeautifulSoup, SoupStrainer
source_code = requests.get('https://stackoverflow.com/')
soup = BeautifulSoup(source_code.content, 'lxml')
links = []
for link in soup.find_all('a'):
links.append(str(link))
Run Code Online (Sandbox Code Playgroud)
问题是,如果我想提取所有 URL,我必须编写另一个 for 循环,然后再编写一个......。我想提取该网站及其子域中存在的所有 URL。有什么办法可以做到这一点而不需要编写嵌套吗?即使使用嵌套的 for 编写,我也不知道应该使用多少个 for 来获取所有 URL。
我正在构建一个网络爬虫,每 30 秒不断刷新一些 etherscan URL,如果发生了任何未考虑到的新传输,它会向我发送一封电子邮件通知和一个指向 etherscan 上相关地址的链接,以便我可以手动检查他们出去。
我想要密切关注的地址之一在这里:
到目前为止我所做的:
from urllib.request import Request, urlopen
url = 'https://etherscan.io/token/0xd6a55c63865affd67e2fb9f284f87b7a9e5ff3bd?a=0x94f52b6520804eced0accad7ccb93c73523af089'
req = Request(url, headers={'User-Agent': 'XYZ/3.0'}) # I got this line from another post since "uClient = uReq(URL)" and "page_html = uClient.read()" would not work (I beleive that etherscan is attemption to block webscraping or something?)
response = urlopen(req, timeout=20).read()
response_close = urlopen(req, timeout=20).close()
page_soup = soup(response, "html.parser")
Transfers_info_table_1 = page_soup.find("div", {"class": "table-responsive"})
print(Transfers_info_table_1)
Run Code Online (Sandbox Code Playgroud)
有趣的是,当我运行它时,我得到以下输出:
<div class="table-responsive" style="visibility:hidden;">
<iframe frameborder="0" id="tokentxnsiframe" scrolling="no" src="" …Run Code Online (Sandbox Code Playgroud) 我编写了一个简单的程序来从https://stats.nba.com抓取数据。我这里的代码工作得非常好,因为它能够完美地从网站获取数据:
chrome_options = webdriver.ChromeOptions()
d = webdriver.Chrome(ChromeDriverManager().install(),options=chrome_options)
d.get('https://stats.nba.com/teams/advanced/?sort=W&dir=-1')
scrape = BeautifulSoup(d.page_source, 'html.parser').find('table')
for row in scrape.find_all('tr'):
for col in row.find_all('td'):
#...more parsing code here
Run Code Online (Sandbox Code Playgroud)
然而,一旦我添加
chrome_options.add_argument('--headless'),整个代码就会失败并且我得到了AttributeError: 'NoneType' object has no attribute 'find_all'。
为什么会出现这种情况?我到处都找过了,但找不到解决方案。谢谢!
编辑:问题似乎是d.page_source为无头和非无头给出了不同的结果。有谁知道为什么会有差异?
python selenium beautifulsoup web-scraping selenium-chromedriver
beautifulsoup ×10
python ×9
python-3.x ×5
web-scraping ×5
web-crawler ×2
etherscan ×1
html ×1
regex ×1
scrapy ×1
selenium ×1
url ×1
urllib ×1