【问题标题】:Removing '\n' from scraped data in Python从 Python 中的抓取数据中删除 '\n'
【发布时间】:2020-02-11 22:46:34
【问题描述】:

我正在从 Github 中抓取 repo 的名称,例如:

repositorys = []
for ulr in user_repo_url: # in this list I have url like ('https://github.com/USER/?tab=repositories)
    source = urllib.request.urlopen(url).read()
    soup = bs.BeautifulSoup(source,'lxml')
    repos = [repo.text for repo in soup.find_all('div',class_='d-inline-block mb-1')]
    repositorys.append(repos)

return render(request,'file.html',{'repositorys':repositorys})

我正在使用 Django 并且一切正常,但是为了获得明文,我得到了名称和 '\n' 符号。我正在尝试使用条带和地图功能,但它们不起作用。您还有其他建议为什么它不起作用?

【问题讨论】:

  • repo.text.strip() ? BS 也有repo.get_text(strip=True) 来删除一些元素之间的\n
  • @furas 是的 - 这很奇怪,但它仅适用于硬编码 URL,并且仅当此 URL 未存储在列表中时才有效
  • 这能回答你的问题吗? Remove all newlines from inside a string

标签: python string


【解决方案1】:

如果您的目标是简单地删除所有出现的\n,您可以改用repo.text.replace('\\n', '')。请注意,如果 \ 是字符串中的字符,则必须对其进行转义,否则,如果要删除换行符,请将其保留为 repo.text.replace('\n', '')。

【讨论】:

  • 它有效 - 不知道为什么它被视为硬编码符号
猜你喜欢
  • 1970-01-01
  • 2021-12-05
  • 2020-05-04
  • 2021-08-19
  • 2013-08-16
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
相关资源
最近更新 更多