首页 > 解决方案 > 美丽的汤输出不是很可读

问题描述

我使用 Beautiful Soup 库创建了一个 twitter 刮板。我已经成功地使用他们的用户名检索了给定用户的 Bio 和热门推文。我遇到的唯一问题是输出有点奇怪,因为输出是从包含许多空行的 HTML 代码中提取的。

我尝试过使用美化,但返回的只是一个空行。我也尝试过使用 pprint.pprint。

我是 python 新手,想不出任何其他方法来使我的脚本输出更整洁

任何帮助将不胜感激。

下面是我的脚本:

import requests
from bs4 import BeautifulSoup
import pprint

q = "https://twitter.com"


def find_bio(username):
    c = format("https://twitter.com"+"/" + username)
    r = requests.get(c)
    s = BeautifulSoup(r.text, "html.parser")

    return s.find("div", class_="ProfileHeaderCard").text


def find_toptweet(username):
    c = format("https://twitter.com"+"/" + username)
    r = requests.get(c)
    s = BeautifulSoup(r.text, "html.parser")

    return s.find("div", class_="content").text


if __name__ == "__main__":
    username = input('enter username: ')
    bio = find_bio(username)
    tweet = find_toptweet(username)
    print("Bio--------------------------------------------------------------")
    pprint.pprint(bio)
    print("End of Bio-------------------------------------------------------")
    print('top tweet')
    pprint.pprint(tweet)

下面的输出

enter username: altifali4
Bio--------------------------------------------------------------------------------------
('\n'
 '\n'
 'Altif Ali\n'
 '\n'
 '\n'
 '\n'
 '@AltifAli4\n'
 '\n'
 '\n'
 'People, by and large, are good people\n'
 '\n'
 'UoH\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
' \n'
 '    instagram.com/altif.ali\n'
 '  \n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Joined August 2018\n'
 '\n'
 '\n'
 '\n'
 '    Born 1999\n'
 '\n'
 '\n'
 '\n')
End of Bio---------------------------------------------------------------- ----------------------
top tweet
('\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Lowkey\u200f\xa0@Lowkey0nline\n'
 '\n'
 'May 22\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'More\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Copy link to Tweet\n'
 '\n'
 '\n'
 'Embed Tweet\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Power concedes nothing without demand. Without demand power concedes '
 'nothing.\n')

Process finished with exit code 0

标签: pythonhtmltwitterpython-3.7

解决方案


尝试用if以下语句替换您的语句:

if __name__ == "__main__":
    username = input('enter username: ')
    bio = find_bio(username).replace("\n","")
    tweet = find_toptweet(username).replace("\n","")
    print("Bio--------------------------------------------------------------")
    print(bio)
    print("End of Bio-------------------------------------------------------")
    print('top tweet')
    print(tweet)

希望这可以帮助


推荐阅读