0

Using python I am trying to get the whole html code of a target CSS selector. The target html code looks like following and I want this whole code:

<img class="card-img-top" src="/svg/2798804.svg" width="200px" height="200px" alt="kitten animal cat " style="user-select: auto;">

My python code :

with open("links.txt", "r") as a_file:
  for line in a_file:
    stripped_line = line.strip()
    endpoint = stripped_line
    start = stripped_line.find('/tag/') + 5
    end = stripped_line.find('.html', start)
    filename = stripped_line[start:end]
    soup = BeautifulSoup(requests.get(endpoint).text)
    completeName = os.path.join(workingpath, filename + ".txt")
    with open(completeName, "w") as f_out:
        for inp in soup.select('.card-img-top'):
            print(inp["value"], file=f_out)
        

Getting this error when running the code:

KeyError: 'value'
1
  • Do you expect the <img> to be an <input>? Commented Aug 28, 2021 at 5:18

1 Answer 1

1

There is no problem with BeautifulSoup. value attribute does not exist in your html fragment (because img has no such attribute, but input has it as suggested by @KlausD.)

>>> inp.attrs
{'class': ['card-img-top'],
 'src': '/svg/2798804.svg',
 'width': '200px',
 'height': '200px',
 'alt': 'kitten animal cat ',
 'style': 'user-select: auto;'}

All possible attributes for img tag can be found here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @corralien I am fairly new in this field. Now it is working fine. But I need to get the 'src' and 'alt' at the same time. Then save to a text file line by line. Can you help me with that. As I said I am new and tried a few ideas but failed.
Succeeded with this "print(inp.attrs["src"], inp.attrs["alt"], sep="\n", file=f_out)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.