python - Python3:如何识别要抓取的“文本”元素,以及如何通过使用类来抓取 URL
问题描述
我目前正在抓取一个网站,并在我试图通过谷歌浏览器的“检查”按钮识别的网页中获取一些详细信息的文本,实际上我能够从普通文本元素中获取我想要的文本。
但是,我有两个问题:
1. 我需要正确获取与正确 div 类关联的文本。正如您在下面的代码中看到的那样,我刚刚输入了“h3”、“p”和“abbr”,并且能够实际获取文本,但是它们并不特定于某个“类”。我想它只是遇到了第一个,这就是为什么在某些网页中我遇到以下错误的原因,因为它指出了错误的元素。
Traceback (most recent call last):
File "C:\Users\admin\Desktop\FolderName\FileName.py", line 18, in <module>
name1 = info2_text.text
AttributeError: 'NoneType' object has no attribute 'text'
所以我想我真正的问题#1 是,为了避免由于错误识别的“p”段落而出现上述错误,如下例所示,我该如何输入代码以根据“类”进行识别?我已经尝试过了info2_text = soup.find('p', attrs={'class': '_5rgt _5nk5 _5msi'})
,但是我只得到了上述错误。
<div class="_5rgt _5nk5 _5msi" style data-gt="{"tn":"*s"}" data-ft="{"tn":"*s"}"> == $0
<span>
<p>
"Sample paragraph"
</p>
2.如何从a href
元素中获取实际的url?在下面的例子中:
<div class="_52jc _5qc4 _78cz _24u0 _36xo" data-sigil="m-feed-voice-subtitle">
<a href="sampleurl.com"></a>
我曾尝试使用,info4_url = soup.find('a', attrs={'class': '_4g34._5i2i._52we'})
但我只能打印'None'
这一行。或者,我看错了 div 类吗?
下面是我尝试使用的实际代码,我想让它尽可能简单。非常感谢你的帮助!
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
import re
import requests
# specify the url
url = 'https://sampleurl.com/'
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
info1_header = soup.find('h3')
info2_text = soup.find('p')
info3_text = soup.find('abbr')
info4_url = soup.find('a')
# Get the data by getting its text
name = info1_header.text
name1 = info2_text.text
name2 = info3_text.text
#print text
print(name)
print(name1)
print(name2)
print(info4_url)
解决方案
仅在相关 div 中查找段落/锚点:
对于第一个问题:
html = '''<div class="_5rgt _5nk5 _5msi" style data-gt="{"tn":"*s"}" data-ft="{"tn":"*s"}"> == $0
<span>
<p>
"Sample paragraph"
</p>'''
soup = BeautifulSoup(html, 'html.parser')
parentDiv = soup.find_all("div", class_="_5rgt _5nk5 _5msi")
for elem in parentDiv:
para = elem.find("p").text
print(para.strip())
输出:
"Sample paragraph"
对于第二个问题:
html = '''<div class="_52jc _5qc4 _78cz _24u0 _36xo" data-sigil="m-feed-voice-subtitle">
<a href="sampleurl.com"></a></div>'''
soup = BeautifulSoup(html, 'html.parser')
for anc in soup.find_all('div', class_="_52jc _5qc4 _78cz _24u0 _36xo"):
anchor = anc.find("a")
print("Found the URL:", anchor['href'])
输出:
Found the URL: sampleurl.com
推荐阅读
- python - Python:在这种情况下如何避免双重循环并加快性能?
- arrays - Kotlin:如何从 Arraylist 中获取列表?
- javascript - 如何让一个有孩子的父母只能在角度上为每个父母选择 1 个孩子
- amazon-web-services - AWS VPC 终端节点设置为 S3 和 DynamoDB
- django-models - 如何在 Django 的序列化程序中使用外键字段?
- android - 在标签布局中居中标签
- flutter - Inkwell 不能与带有装饰的容器一起正常工作
- flutter - Dart,Flutter:异常:键入“列表”
' 不是类型 'Map 的子类型 ' 在类型转换中 - xaml - Xamarin 表单按钮计数单击导航
- scrapy - 如何在 Scrapy 中将参数字典作为蜘蛛参数传递?