[英]How to fix error: AttributeError: 'str' object has no attribute 'text'
[英]AttributeError: 'str' object has no attribute 'text' printing css error
我正在尝试打印作业的文本。 不幸的是,href 一直不显示,我在打印文本时不断出错,我收到以下错误:
Traceback (most recent call last):
File "C:/Users/Bain3/PycharmProjects/untitled4/Bookmaker improved ALTERNATIVE.py",
line 155, in <module>
print(bet.text)
AttributeError: 'str' object has no attribute 'text'
下面的代码或完整的代码在这里
with open('Aperture Science.csv', 'a+', newline='\n') as file:
writer = csv.writer(file)
for section in sections:
try:
link = section.find_element_by_css_selector("h3 a").get_attribute("href")
print((section.get_attribute('href')))
except NoSuchElementException:
pass
time.sleep(7)
try:
team_name = section.find_element_by_css_selector(".row:nth-child(1) td:nth-child(1)").text
print(section.text)
except NoSuchElementException:
pass
time.sleep(7)
try:
bet = section.find_element_by_css_selector(".odds .odds span").text
print(bet.text)
except NoSuchElementException:
pass
time.sleep(7)
writer.writerow((bet, team_name, link))
我尝试过类似的变体:
for section in sections:
try:
link = section.find_element_by_css_selector("h3 a").get_attribute("href")
print((link.get_attribute('href')))
也:
team_name = section.find_element_by_css_selector(".row:nth-child(1) td:nth-child(1)").text
print(team_name.text)
print(section.text)
有效,尽管这不是我想要打印的文本。 有任何想法吗?
bet = section.find_element_by_css_selector(".odds .odds span").text
已经返回了第一个节点的文本值。
如果要打印文本值列表,则需要使用find_elements
而不是find_element
,如下所示:
links = [link.get_attribute("href") for link in section.find_elements_by_css_selector("h3 a")]
team_names = [team_name.text for team_name in section.find_elements_by_css_selector(".row:nth-child(1) td:nth-child(1)")]
bets = [bet.text for bet in section.find_elements_by_css_selector(".odds .odds span")]
writer.writerow(bets, team_names, links)
如果 team_name 是 sth 的文本,那么 print(team_name) 就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.