Python - 在同一行上打印

4

我是一个新手,正在尝试学习如何抓取表格数据。我有以下代码,但无法将两个变量打印在同一行上;它们会分别打印在不同的行上。我错过了什么吗?

from lxml import html
from bs4 import BeautifulSoup
import requests

url = "http://www.columbia.edu/~fdc/sample.html"

r = requests.get(url)

soup = BeautifulSoup(r.content)

tables = soup.findAll('table')

for table in tables:
    Second_row_first_column = table.findAll('tr')[1].findAll('td')[0].text
    Second_row_second_column = table.findAll('tr')[1].findAll('td')[1].text
    print Second_row_first_column + Second_row_second_column

1
你能展示一下样本输出吗?也许你的字符串末尾有一个换行符。 - sshashank124
@sshashank124 你是对的,我误读了OP想要做什么。撤回关闭投票。 - MattDMo
1
你还应该避免重复调用同一个函数。将 table.findAll('tr')[1].findAll('td') 存储在一个变量中,然后分别使用 my_var[0].textmy_var[1].text - sshashank124
2个回答

4

这些列在末尾有一个换行符,如果您想在不包含它们的情况下打印它们,您需要使用.strip()函数:

print Second_row_first_column.strip() + Second_row_second_column.strip()

如果您想在两列之间添加空格,请用逗号替换加号。

啊,非常感谢!我花了好几个小时才弄明白这个问题! - JohnR4785

0

我认为你应该使用这个:

Second_row_first_column = table.findAll('tr')[1].findAll('td')[0].text.rstrip('\n') + "\t"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接