Python 使用beautifulsoup提取属性值

Python 使用beautifulsoup提取属性值,python,parsing,attributes,beautifulsoup,Python,Parsing,Attributes,Beautifulsoup,我试图提取网页上特定“输入”标记中单个“值”属性的内容。我使用以下代码: 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"

我试图提取网页上特定“输入”标记中单个“值”属性的内容。我使用以下代码:

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)
我得到一个类型错误:列表索引必须是整数,而不是str

尽管从Beautifulsoup文档中我了解到字符串在这里不应该是一个问题。。。但我不是专家,我可能误解了

非常感谢您的任何建议

.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']

我建议您使用一种节省时间的方法,假设您知道什么样的标记具有这些属性

假设一个标记xyz将该属性命名为“staininfo”

我想让你明白完整的标签是一个列表

for each_tag in full_tag:
    staininfo_attrb_value = each_tag["staininfo"]
    print staininfo_attrb_value

因此,您可以获取所有标记xyz的staininfo的所有属性值。如果您想从上述源中检索多个属性值,您可以使用
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.

python3.x
中,只需在使用
find\u all
获得的标记对象上使用
get(attr\u name)

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)
针对XML文件
conf//test1.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>

您还可以使用以下选项:

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)

我在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])
从bs4导入美化组
html=“”
bsoup=beautifulsop(html,'html.parser')
对于bsoup中的td.find_all('td'):
如果td.has_attr('class'):
打印(td['class'][0])
请务必注意,即使属性只有一个值,属性键也会检索列表。

对于我来说:

<input id="color" value="Blue"/>

您可以尝试使用名为requests\u html的功能强大的新软件包:

来自请求\u html导入HTMLSession
session=HTMLSession()
r=会话。获取(“https://www.bbc.co.uk/news/technology-54448223")
date=r.html.find('time',first=True)#查找名为“time”的“标记”
打印(日期)#您将拥有:
#要获取“datetime”属性内的文本,请使用:
打印(date.attrs['datetime'])#您将获得'2020-10-07T11:41:22.000Z'
您可以尝试:

使用
pip安装gazpacho

获取HTML并使用以下方法制作

从gazpacho进口获得,汤
汤http://ip.add.ress.here/)#get直接返回html
inputs=soup.find('input',attrs={'name':'stainfo'})#查找所有输入标记
如果输入:
如果类型(输入)为列表:
对于输入中的输入:
打印(input.attr.get('value'))
其他:
打印(inputs.attr.get('value'))
其他:
打印('未找到具有属性name=“stainfo”的标记)

以下是一个示例,说明如何提取所有
a
标记的
href
属性:

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)

好东西!谢谢现在我有一个关于解析输出的问题,我需要一长串非ASCII字符,但我将在另一个问题中提出这个问题。是否应该按照访问“值”。在这种情况下,是什么使上述代码起作用的?我认为您必须通过执行
output=inputTag[0]来访问该值。contents
@Seth-no,因为他正在查找输入标记的attrib'value',并且.contents返回由标记封装的文本(I am.contents)--(现在只是回复,因为我必须仔细检查发生了什么;估计其他人可能会受益)回答得很好。但是,我会使用
inputTag[0].get('value')
而不是
inputTag[0]['value']
,以防止在标签作为无值属性的情况下出现无指针。关于没有直接链接到访问网站主页的链接,如何获得所有链接,无论是直接链接还是间接链接到网页。您介意我按照PEP 8进行编辑,并使用更现代的字符串格式方法吗?很好,去吧。这是最有用和最清楚的答案。应该是被接受的答案这与已经在这里的更老的答案有什么不同?你在哪里定义
color
?我猜,他忘了使用
colorName['value']
而不是
color['value']
<input id="color" value="Blue"/>
page = requests.get("https://www.abcd.com")
soup = BeautifulSoup(page.content, 'html.parser')
colorName = soup.find(id='color')
print(color['value'])
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'
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)