Python编写一个简单的爬虫程序
发布时间:2023-12-04 12:59:36
Python编写一个简单的爬虫程序可以使用requests和beautifulsoup这两个库来实现。
使用requests库发送HTTP请求,获取网页内容,并使用beautifulsoup库解析网页。
下面是一个简单的爬虫程序的示例:
import requests
from bs4 import BeautifulSoup
# 发送HTTP请求,获取网页内容
def get_html(url):
try:
response = requests.get(url)
response.raise_for_status()
response.encoding = response.apparent_encoding
return response.text
except:
return ""
# 解析网页,提取需要的信息
def parse_html(html):
try:
soup = BeautifulSoup(html, 'html.parser')
# 这里可以根据网页结构和需求,使用不同的选择器提取相应的信息
titles = soup.select('.title')
for title in titles:
print(title.text)
except:
print("解析失败")
# 主函数
def main():
url = "http://www.example.com" #需要爬取的网页URL
html = get_html(url)
parse_html(html)
if __name__ == '__main__':
main()
以上程序中,get_html()函数使用requests库发送HTTP请求获取网页内容,parse_html()函数使用beautifulsoup库解析网页,并提取需要的信息。
在主函数中,首先设定需要爬取的网页URL,然后调用get_html()获取网页内容,再使用parse_html()解析网页并提取信息。最后将获得的信息进行处理,如打印输出。
请注意在实际应用中,需要根据具体的网页结构和需求进行相应的修改。另外,通过添加循环和分页处理等功能,可以实现更加复杂和全面的爬虫程序。
