【问题标题】:Separating the content from rquests.text to separate rows将 requests.text 中的内容分离为单独的行
【发布时间】:2014-05-03 19:46:32
【问题描述】:

我开始使用请求模块。我不明白为什么这样的输出:

import requests

r = requests.get("https://www.kickstarter.com/")   # kickstarter just as an example

content = r.text  

for rownum, row in enumerate(content):
    print rownum,row

将产生一个行号和一个字符。我怎样才能得到更像网站原始版本的东西(即,如果你去网站并点击“查看源代码”,你会得到什么)

干杯!

【问题讨论】:

  • 是的,显然原因很简单——内容只是一个长字符串,需要用 content..split('\n') 分割成行

标签: python request web-scraping httprequest


【解决方案1】:

如果您想从网页中获取数据,我建议您使用 BeautifulSoup 之类的内容。

下面有几个示例,请查看链接以获取更多示例。

import requests
from bs4 import BeautifulSoup
r = requests.get("https://www.kickstarter.com/")   # kickstarter just as an example
soup = BeautifulSoup(r.text)
print soup.title
print soup.title.name
print soup.find_all('a')

short tut for using Bsoup and requests

【讨论】:

  • 感谢您的回复。我看到你还在使用 requests 模块,那么 beautifulsoup 有什么贡献呢? tnx
  • requests 获取网页,Beautifulsoup 用于解析它,我在 Web 相关开发方面经验很少,但是使用 requests 和 Beautifulsoup 使我不得不做的很多事情变得非常容易。我添加了一个关于在 Beautifulsoup 中使用请求的简短教程
猜你喜欢
  • 1970-01-01
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 2017-03-14
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多