Python抓取网页源代码
时间: 2023-03-28 20:01:56 浏览: 83
你可以使用 Python 的 requests 库来抓取网页源代码,具体方法可以参考以下代码:
```python
import requests
url = 'http://www.example.com'
response = requests.get(url)
html = response.text
print(html)
```
其中,url 是你要抓取的网页地址,response 是服务器返回的响应对象,html 是网页的源代码。
相关问题
Python抓取网页源代码的方法
Python抓取网页源代码的方法有很多种,其中使用第三方库requests是比较常用的一种方法。使用requests库可以通过以下两行代码获取网页的源代码:
import requests
source = requests.get('网址').content.decode()
其中,第一行代码导入了requests库,第二行代码使用requests.get()方法获取网页的源代码,并使用.content.decode()将bytes型的网页源代码解码为字符串型的源代码。此外,还可以使用其他方法获取网页源代码,例如使用Python自带的urllib库、使用第三方库BeautifulSoup等。
python获取网页源代码
您可以使用 Python 的 requests 库来获取网页源代码。以下是一个简单的示例代码:
```python
import requests
url = 'https://www.example.com'
response = requests.get(url)
if response.status_code == 200:
html_code = response.text
print(html_code)
else:
print(f'Request failed with status code {response.status_code}')
```
在上面的代码中,我们首先使用 requests 库向指定的 URL 发送 GET 请求。如果请求成功,我们可以通过 response 对象的 text 属性来获取网页的源代码。最后,我们可以将源代码打印出来或进行其他操作。