【问题标题】:AttributeError: 'str' object has no attribute 'text' printing css errorAttributeError:'str'对象没有属性'text'打印css错误
【发布时间】:2018-04-06 00:22:10
【问题描述】:

我正在尝试打印作业的文本。不幸的是,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'

以下代码或完整代码here

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...(....).text,然后期望bet.text 存在?

标签: python python-3.x csv selenium web-scraping


【解决方案1】:

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)

【讨论】:

  • 谢谢!尽管 csv 看起来不正确,但在控制台中工作正常ibb.co/hm2YMR
  • 输出应该是什么样子?删除空字符串?
  • 试试writer.writerow(bets[0], team_names[0], links[0])
  • 嗯似乎也不喜欢那样。我在这里发布了我的完整代码和错误pastebin.com/fKtkNCG5
  • writer.writerow((bets[0], team_names[0], links[0]))
【解决方案2】:

如果 team_name 是某事的文本,那么 print(team_name) 就足够了。

【讨论】:

  • 差不多了。它只为我打印一个文本,因为我需要一个列表
猜你喜欢
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 2023-04-07
  • 2018-03-15
  • 1970-01-01
  • 2023-03-05
  • 2020-09-28
  • 1970-01-01
相关资源
最近更新 更多