用python写爬虫代码
时间: 2023-06-11 18:07:45 浏览: 49
以下是一个简单的Python爬虫代码示例,可以爬取指定网站的HTML页面:
```python
import requests
# 设置请求头,模拟浏览器访问
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299"
}
# 发送请求,获取网页内容
url = "https://www.example.com"
response = requests.get(url, headers=headers)
html_content = response.text
# 解析网页内容
# TODO: 解析HTML页面,获取需要的数据
```
在上面的代码中,我们使用requests库发送HTTP GET请求,获取指定网站的HTML页面内容。我们还设置了一个请求头,以模拟浏览器访问的方式,避免被网站识别为爬虫。最后,我们可以使用第三方库(如BeautifulSoup)来解析HTML页面,获取需要的数据。
相关问题
用python写一下爬虫代码
当然,下面是一个使用Python编写的简单爬虫代码,用于获取网页内容:
```python
import requests
def get_html(url):
try:
response = requests.get(url)
response.raise_for_status()
return response.text
except requests.exceptions.RequestException as e:
print("请求出错: ", e)
# 在这里调用函数并传入要爬取的网页链接
html = get_html("https://www.example.com")
print(html)
```
上述代码使用了`requests`库来发送HTTP请求,并获取网页的内容。`get_html`函数接受一个URL作为参数,发送GET请求,并返回响应的HTML内容。如果请求发生错误,它会抛出一个异常并打印错误信息。
你可以将代码中的`"https://www.example.com"`替换为你想要爬取的网页链接,然后运行代码即可获取网页内容并打印出来。
需要注意的是,爬取网页时要遵守网站的爬虫规则,并尊重网站的隐私政策。另外,有些网站可能会对爬虫进行限制或防护措施,请确保你的爬虫行为合法并遵守相关规定。
用python写个爬虫代码
好的,以下是一个简单的 Python 爬虫代码,可以用来获取指定网站的标题和链接:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
print(link.string)
```
注:这只是一个简单的演示代码,实际爬取网站时需要注意法律法规以及网站的使用协议,避免侵犯他人利益。