Beautifulsoup-在soup.find()中传递变量 [英] Beautifulsoup - Pass variables in soup.find()

查看:108
本文介绍了Beautifulsoup-在soup.find()中传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

result = soup.find('span', {'id': 'dlROA_ctl35_lblROALINE'}).get_text()

我想通过使用变量使其动态来做与上述相同的事情.我正在使用以下代码,但是它不起作用:

I want to do the same thing as above by using variables to make it dynamic. I am using the following piece of code, but it does not work:

i = 135
idstring = 'dlROA_ct'+str(i)+'_lblROALINE'
dict1 = {'id': idstring}
result = soup.find('span', dict1).get_text()

我收到错误消息:"AttributeError:'NoneType'对象没有属性'get_text'"

I am getting the error: "AttributeError: 'NoneType' object has no attribute 'get_text'"

推荐答案

似乎您正在尝试使用迭代器查找包含该字符串的所有跨度.您可以根据需要执行此操作,但是更好的解决方案是传递正则表达式,如下所示:

It looks as though you are attempting to set up to use an iterator to find all occurrences of the spans containing that string. You can do that if you like, but a better solution would be to pass in a regular expression like the following:

import re

results = soup.find_all('span', {'id': re.compile('dlROA_ctl\d+_lblROALINE')})
for result in results:
    print(result.get_text())

有关正则表达式的快速参考,我建议 https://regex101.com

For a quick reference on regular expressions I recommend https://regex101.com

要回答您实际上提出的问题:

To answer the question you actually posed though:

出现属性错误的原因不是因为代码未正确接受变量,而是因为您要获取的源代码不包含您指定的标签.

The reason you are getting an attribute error is not because the code is not properly accepting your variable, but because the source code you are turning to soup does not contain the tag you are specifying.

要避免出现属性错误,可以执行以下操作:

To keep from getting the attribute error you are getting you can instead do the following:

i = 35
idstring = 'dlROA_ctl'+str(i)+'_lblROALINE'
dict1 = {'id': idstring}
result = soup.find('span', dict1)
if result:
    print(result.get_text())
else:
    print('no result found')

如果仍然找不到结果,则可能要考虑汤不是您想的那样,并且可能要查看soup.prettify()

If you continue to get no result found you may want to consider that soup is not what you think it is and may want to look at soup.prettify()

这篇关于Beautifulsoup-在soup.find()中传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆