简体   繁体   English

如何在 Pycharm 中使用 requests 模块?

[英]How do I use the requests module within Pycharm?

I'm new to Python, and I'm working in Pycharm to read data line by line from a webpage.我是 Python 的新手,我正在 Pycharm 从网页逐行读取数据。 For this task, I'm attempting to use the requests module.对于这个任务,我正在尝试使用 requests 模块。 However, when I try to print the response object, I see "Process finished with exit code 0" and no object displayed.但是,当我尝试打印响应 object 时,我看到“进程以退出代码 0 完成”并且没有显示 object。

Do I need to create some sort of setting to be able to work with HTTP requests in Python?我是否需要创建某种设置才能处理 Python 中的 HTTP 请求?

Code:代码:

import re
import requests 

def find_phone_number(url='https://www.python-course.eu/barneyhouse.txt'):
    response = requests.get(url)
    return response


    print(find_phone_number(url='https://www.python-course.eu/barneyhouse.txt'))

You need to call the function and access the 'text' element.您需要调用 function 并访问“文本”元素。

Also, in your code the print statement is not indented properly so it will never be run.此外,在您的代码中,打印语句没有正确缩进,因此它永远不会运行。

Here is an example of the code doing what I think you intendend:这是执行我认为您想要的代码的示例:

import re
import requests 

def find_phone_number(url='https://www.python-course.eu/simpsons_phone_book.txt'):
    response = requests.get(url)
    return response
    
text_you_want = find_phone_number().text
print(text_you_want)

Well, for starters, your find_phone_number() function calls itself after it returns.好吧,对于初学者来说,您的find_phone_number() function 在返回后会调用自己。 This is because your last line is indented and therefore inside the function definition.这是因为您的最后一行是缩进的,因此在 function 定义内。 The reason you keep getting Process finished with exit code 0 is because your function is never actually called.您继续Process finished with exit code 0的原因是因为您的 function 从未真正被调用过。 This should work:这应该有效:

import re
import requests 

def find_phone_number(url='https://www.python-course.eu/barneyhouse.txt'):
    response = requests.get(url)
    return response

print(find_phone_number(url='https://www.python-course.eu/barneyhouse.txt'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM