【问题标题】:Why is my text running down the screen instead of across in Python Terminal?为什么我的文本在屏幕上运行而不是在 Python 终端中运行?
【发布时间】:2020-03-21 11:43:19
【问题描述】:
soup = BeautifulSoup(requests.get(url).text, 
'html.parser')
for tr in soup.findAll("table"):
    for td in tr.find_all("a"):
        table = str(td.text)
        print(table)

Code
International
Languages
England
en
enk
Welsh
wk
wkk
France
fr
fk

为什么打印如下,我真正想看到下面的输出作为一个列表:

['Code', 'International', 'Languages', 'England', 'en', 'enk', 'Welsh', 'wk', 'wkk', 'France', 'fr', 'fk']

【问题讨论】:

    标签: python list beautifulsoup


    【解决方案1】:
    table = [] 
    for tr in soup.findAll("table"):
        for td in tr.find_all("a"):
            table.append(str(td.text))
    print table
    

    【讨论】:

      【解决方案2】:

      那是因为您正在逐项打印,并且每个 print 都在打印的数据之后使用换行符(除非使用 end 参数明确更改)。要得到你想要的东西:

      soup = BeautifulSoup(requests.get(url).text, 'html.parser')
      print([str(td.text) for tr in soup.findAll("table") for td in tr.find_all("a")])
      

      【讨论】:

        猜你喜欢
        • 2022-11-23
        • 1970-01-01
        • 2017-03-28
        • 2021-11-21
        • 2022-01-14
        • 2021-09-14
        • 1970-01-01
        • 1970-01-01
        • 2019-05-25
        相关资源
        最近更新 更多