Extracting an attribute value with beautifulsoup

前端 未结 9 1920
故里飘歌
故里飘歌 2020-11-22 04:38

I am trying to extract the content of a single \"value\" attribute in a specific \"input\" tag on a webpage. I use the following code:

import urllib
f = urll         


        
相关标签:
9条回答
  • 2020-11-22 05:42

    For me:

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

    This can be fetched by below snippet.

    page = requests.get("https://www.abcd.com")
    soup = BeautifulSoup(page.content, 'html.parser')
    colorName = soup.find(id='color')
    print(color['value'])
    
    0 讨论(0)
  • 2020-11-22 05:43

    In Python 3.x, simply use get(attr_name) on your tag object that you get using 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)
    

    against XML file conf//test1.xml that looks like:

    <?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>
    

    prints:

    Processing repElem...
    Attribute id = 11
    Attribute name = Joe
    Processing repElem...
    Attribute id = 12
    Attribute name = Mary
    
    0 讨论(0)
  • 2020-11-22 05:43

    you can also use this :

    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)
    
    0 讨论(0)
提交回复
热议问题