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

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:列表索引必须是整数,而不是str

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

任何建议都非常感谢!


当前回答

如果你想从上面的源代码中检索多个属性值,你可以使用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.

其他回答

对我来说:

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

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

你可以试试西班牙凉菜汤:

使用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")

你也可以用这个:

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)

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

假设标签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值