python - 美丽的汤输出不是很可读
问题描述
我使用 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
解决方案
尝试用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)
希望这可以帮助
推荐阅读
- sql - 从用户输入中读取日期并传递给两个函数
- php - PHP - 获取数据时的标头重定向
- python - Python:用来自多个嵌套for循环的数据编写csv
- apache-spark - 删除后如何避免火花数据框中的列名不明确
- perl - 在 @INC 中找不到 scripts/Config.pm(您可能需要安装 scripts::Config 模块)
- sql - 为什么允许在表名后面使用“from”?它有什么作用?
- docker - Divio 应用程序或 CLI“医生”报告 DNS 故障
- docker - 在 docker 上运行的 aspnet 核心和 vue 项目中的 npm 包静态文件路径问题
- typescript - 如何在 TypeScript 中键入 PublicKeyCredential?
- postgresql - 加快代价高昂的连接操作 - 大表和小表