使用 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 Beautiful...

问题描述:

我正在尝试提取网页上特定“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")
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用