使用beautifulsoup提取属性值

Bar*_*abe 88 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" : "stainfo"})

output = inputTag['value']

print str(output)
Run Code Online (Sandbox Code Playgroud)

我得到一个TypeError:列表索引必须是整数,而不是str

即使从Beautifulsoup文档我明白字符串不应该是一个问题...但我没有专家,我可能会误解.

任何建议都非常感谢!提前致谢.

Łuk*_*asz 122

.findAll() 返回所有找到的元素的列表,所以:

inputTag = soup.findAll(attrs={"name" : "stainfo"})
Run Code Online (Sandbox Code Playgroud)

inputTag是一个列表(可能只包含一个元素).根据您的具体需求,您应该做:

 output = inputTag[0]['value']
Run Code Online (Sandbox Code Playgroud)

或者使用.find()只返回一个(第一个)找到元素的方法:

 inputTag = soup.find(attrs={"name": "stainfo"})
 output = inputTag['value']
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案。但是,我会使用 `inputTag[0].get('value')` 而不是 `inputTag[0]['value']` 来防止标签没有值属性时出现无指针 (3认同)
  • 不应该根据http://stackoverflow.com/questions/2616659/extracting-value-in-beautifulsoup访问"价值".是什么让上面的代码在这种情况下工作?我认为你必须通过`output = inputTag [0] .contents`来访问该值 (2认同)

vij*_*j34 23

为我:

<input id="color" value="Blue"/>
Run Code Online (Sandbox Code Playgroud)

这可以通过下面的代码片段获取。

page = requests.get("https://www.abcd.com")
soup = BeautifulSoup(page.content, 'html.parser')
colorName = soup.find(id='color')
print(colorName['value'])
Run Code Online (Sandbox Code Playgroud)


amp*_*ent 15

在中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)
Run Code Online (Sandbox Code Playgroud)

针对如下的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>
Run Code Online (Sandbox Code Playgroud)

印刷品:

Processing repElem...
Attribute id = 11
Attribute name = Joe
Processing repElem...
Attribute id = 12
Attribute name = Mary
Run Code Online (Sandbox Code Playgroud)

  • 您介意我编辑它以遵循 PEP 8 并使用更现代的字符串格式化方法吗? (2认同)

小智 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)
Run Code Online (Sandbox Code Playgroud)


小智 5

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

假设标签 xyz 具有名为“staininfo”的属性。

full_tag = soup.findAll("xyz")
Run Code Online (Sandbox Code Playgroud)

我不想让你明白 full_tag 是一个列表

for each_tag in full_tag:
    staininfo_attrb_value = each_tag["staininfo"]
    print staininfo_attrb_value
Run Code Online (Sandbox Code Playgroud)

因此,您可以获得所有标签xyz的staininfo的所有attrb值


小智 5

如果要从上面的源中检索属性的多个值,可以使用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.
Run Code Online (Sandbox Code Playgroud)


Yas*_*r M 5

您可以尝试使用名为requests_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'
Run Code Online (Sandbox Code Playgroud)