list() 在一行中,不能引入 /newlines



作为一个项目,我正在编写代码,用游戏中某些怪物的统计数据来抓取网站,问题是,当我将数据附加到列表中时,它会以很长的单行形式打印出来。我已经尝试过.append(clean_data.getText((.replace('\n',"\\n"(。需要考虑的是,如果我不使用.getText((,我会在列表中添加很多[td]和[tr]标签,这会变得非常混乱。我认为这里的问题是,我得到的文本被视为纯文本,所以当我用\\n替换\n时,它会被直接替换为\\n,就像它不识别\\n一样。

我的代码:

import requests
import pandas as pd
from bs4 import BeautifulSoup
import csv
url = 'https://guildstats.eu/monsters?world=Yonabra'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
monsters = ('adult goannas', 'young goannas', 'manticores', 'feral sphinxes', 'ogre ruffians', 'ogre rowdies', 'ogre sages', 'dogs')
finding_td = soup.find_all('td', string=monsters)
list_of_monsters = []
for looking_for_parent in finding_td:
parent_tr = looking_for_parent.find_parents('tr')
for clean_data in parent_tr:
list_of_monsters.append(clean_data.getText().replace('n', " "))
print(list_of_monsters)

它给出以下输出:

[' 7 adult goannas  2020-05-28 1519 0 736893 133 ', ' 222 dogs  2020-05-27 143 0 40043 0 ', ' 298 feral sphinxes  2020-05-28 1158 1 480598 152 ', ' 498 manticores  2020-05-28 961 1 299491 68 ', ' 581 ogre rowdies  2020-05-28 306 0 188324 13 ', ' 582 ogre ruffians  2020-05-29 217 0 121964 7 ', ' 583 ogre sages  2020-05-28 156 0 63489 8 ', ' 911 young goannas  2020-05-28 1880 0 972217 74 ']

我希望它更像这样:

[' 7 adult goannas  2020-05-28 1519 0 736893 133 '
' 222 dogs  2020-05-27 143 0 40043 0 '
' 298 feral sphinxes  2020-05-28 1158 1 480598 152 '
' 498 manticores  2020-05-28 961 1 299491 68 '
' 581 ogre rowdies  2020-05-28 306 0 188324 13 '
' 582 ogre ruffians  2020-05-29 217 0 121964 7 '
' 583 ogre sages  2020-05-28 156 0 63489 8 '
' 911 young goannas  2020-05-28 1880 0 972217 74 ']

您想要的是更改数组的分隔符,而不是,,您想要一个新行。正如@QHarr所提到的,您可以使用pythonpprint以更好的格式打印结果。

尝试:

import requests
import pandas as pd
from bs4 import BeautifulSoup
import csv
from pprint import pprint
url = 'https://guildstats.eu/monsters?world=Yonabra'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
monsters = ('adult goannas', 'young goannas', 'manticores', 'feral sphinxes', 'ogre ruffians', 'ogre rowdies', 'ogre sages', 'dogs')
finding_td = soup.find_all('td', string=monsters)
list_of_monsters = []
for looking_for_parent in finding_td:
parent_tr = looking_for_parent.find_parents('tr')
for clean_data in parent_tr:
list_of_monsters.append(clean_data.getText().replace("n", " "))
pprint(list_of_monsters)

这给出:

[' 7 adult goannas  2020-05-28 1519 0 736893 133 ',
' 222 dogs  2020-05-27 143 0 40043 0 ',
' 298 feral sphinxes  2020-05-28 1158 1 480598 152 ',
' 498 manticores  2020-05-28 961 1 299491 68 ',
' 581 ogre rowdies  2020-05-28 306 0 188324 13 ',
' 582 ogre ruffians  2020-05-29 217 0 121964 7 ',
' 583 ogre sages  2020-05-28 156 0 63489 8 ',
' 911 young goannas  2020-05-28 1880 0 972217 74 ']

您获得的n字符已经是换行符。没有必要在python中添加额外的转义字符。正如您所尝试的,replace("n", " ")已经为您提供了所需的replace效果。此外,由于您正在打印一个数组,即使元素以新行结束,它仍将打印为npprint不会对原始数组产生任何影响,只会以更好的格式打印。

最新更新