使用 beautifulsoup 提取属性值
- 2024-12-11 08:48:00
- admin 原创
- 140
问题描述:
我正在尝试提取网页上特定“input”标签中单个“value”属性的内容。我使用以下代码:
import urllib
f = urllib.urlopen("http://58.68.130.147")
s = f.read()
f.close()
from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(s)
inputTag = soup.findAll(attrs={"name" : "stainfo"})
output = inputTag['value']
print str(output)
我明白了TypeError: list indices must be integers, not str
尽管从 Beautifulsoup 文档中,我了解到字符串在这里不应该成为问题……但我不是专家,我可能误解了。
非常感谢您的任何建议!
解决方案 1:
.find_all()
返回所有找到的元素的列表,因此:
input_tag = soup.find_all(attrs={"name" : "stainfo"})
input_tag
是一个列表(可能只包含一个元素)。根据你的需求,你可以执行以下操作:
output = input_tag[0]['value']
或使用.find()
仅返回一个(第一个)找到的元素的方法:
input_tag = soup.find(attrs={"name": "stainfo"})
output = input_tag['value']
解决方案 2:
在中Python 3.x
,只需get(attr_name)
在您获取的标签对象上使用即可find_all
:
xmlData = None
with open('conf//test1.xml', 'r') as xmlFile:
xmlData = xmlFile.read()
xmlDecoded = xmlData
xmlSoup = BeautifulSoup(xmlData, 'html.parser')
repElemList = xmlSoup.find_all('repeatingelement')
for repElem in repElemList:
print("Processing repElem...")
repElemID = repElem.get('id')
repElemName = repElem.get('name')
print("Attribute id = %s" % repElemID)
print("Attribute name = %s" % repElemName)
conf//test1.xml
针对如下XML 文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<singleElement>
<subElementX>XYZ</subElementX>
</singleElement>
<repeatingElement id="11" name="Joe"/>
<repeatingElement id="12" name="Mary"/>
</root>
印刷:
Processing repElem...
Attribute id = 11
Attribute name = Joe
Processing repElem...
Attribute id = 12
Attribute name = Mary
解决方案 3:
为我:
<input id="color" value="Blue"/>
可以通过以下代码片段获取。
page = requests.get("https://www.abcd.com")
soup = BeautifulSoup(page.content, 'html.parser')
colorName = soup.find(id='color')
print(colorName['value'])
解决方案 4:
如果您想从上面的源中检索属性的多个值,您可以使用findAll
列表推导来获取所需的一切:
import urllib
f = urllib.urlopen("http://58.68.130.147")
s = f.read()
f.close()
from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(s)
inputTags = soup.findAll(attrs={"name" : "stainfo"})
### You may be able to do findAll("input", attrs={"name" : "stainfo"})
output = [x["stainfo"] for x in inputTags]
print output
### This will print a list of the values.
解决方案 5:
实际上,我会建议您采用一种节省时间的方法来做到这一点,假设您知道哪种标签具有这些属性。
假设标签 xyz 具有名为“staininfo”的属性。
full_tag = soup.findAll("xyz")
我想让你明白 full_tag 是一个列表
for each_tag in full_tag:
staininfo_attrb_value = each_tag["staininfo"]
print staininfo_attrb_value
因此,您可以获得所有标签 xyz 的 staininfo 的所有 attrb 值
解决方案 6:
你也可以使用这个:
import requests
from bs4 import BeautifulSoup
import csv
url = "http://58.68.130.147/"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, "html.parser")
get_details = soup.find_all("input", attrs={"name":"stainfo"})
for val in get_details:
get_val = val["value"]
print(get_val)
解决方案 7:
您可以尝试使用名为request_html的新的强大包:
from requests_html import HTMLSession
session = HTMLSession()
r = session.get("https://www.bbc.co.uk/news/technology-54448223")
date = r.html.find('time', first = True) # finding a "tag" called "time"
print(date) # you will have: <Element 'time' datetime='2020-10-07T11:41:22.000Z'>
# To get the text inside the "datetime" attribute use:
print(date.attrs['datetime']) # you will get '2020-10-07T11:41:22.000Z'
解决方案 8:
我将其与 Beautifulsoup 4.8.1 一起使用来获取某些元素的所有类属性的值:
from bs4 import BeautifulSoup
html = "<td class='val1'/><td col='1'/><td class='val2' />"
bsoup = BeautifulSoup(html, 'html.parser')
for td in bsoup.find_all('td'):
if td.has_attr('class'):
print(td['class'][0])
值得注意的是,即使属性只有一个值,属性键也会检索列表。
解决方案 9:
下面是一个如何提取href
所有a
标签属性的例子:
import requests as rq
from bs4 import BeautifulSoup as bs
url = "http://www.cde.ca.gov/ds/sp/ai/"
page = rq.get(url)
html = bs(page.text, 'lxml')
hrefs = html.find_all("a")
all_hrefs = []
for href in hrefs:
# print(href.get("href"))
links = href.get("href")
all_hrefs.append(links)
print(all_hrefs)
解决方案 10:
如果你有这样的标签:
<input type="text"/>
在变量输入中,您可以使用以下命令获取属性“type”的值:
type = input.get("type")
解决方案 11:
您可以尝试西班牙凉菜汤:
使用安装pip install gazpacho
获取 HTML 并使用Soup
:
from gazpacho import get, Soup
soup = Soup(get("http://ip.add.ress.here/")) # get directly returns the html
inputs = soup.find('input', attrs={'name': 'stainfo'}) # Find all the input tags
if inputs:
if type(inputs) is list:
for input in inputs:
print(input.attr.get('value'))
else:
print(inputs.attr.get('value'))
else:
print('No <input> tag found with the attribute name="stainfo")