欢迎访问宙启技术站
智能推送

Python爬虫中常用的函数及示例

发布时间:2023-06-07 17:09:59

Python爬虫中常用的函数有很多,以下是其中的一些:

1. requests.get(url):用于发送HTTP请求并获取网页的HTML源码。例如:

import requests
url = 'http://www.example.com'
response = requests.get(url)
print(response.text)

2. BeautifulSoup(html, 'html.parser'):用于解析HTML源码。例如:

from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')

3. soup.find_all(tag, attrs):用于按照标签名和属性查找HTML元素。例如:

links = soup.find_all('a')
for link in links:
    print(link.get('href'))

4. re.findall(pattern, string):用于按照正则表达式查找字符串中的内容。例如:

import re
emails = re.findall(r'\w+@\w+.\w+', response.text)
for email in emails:
    print(email)

5. urllib.request.urlretrieve(url, filename):用于将网页上的文件下载到本地。例如:

import urllib.request
url = 'http://www.example.com/images/logo.png'
filename = 'logo.png'
urllib.request.urlretrieve(url, filename)

6. pandas.read_html(url):用于从HTML表格中读取数据并转换成Dataframe格式。例如:

import pandas as pd
url = 'http://www.example.com/table.html'
dfs = pd.read_html(url)
for df in dfs:
    print(df.head())

7. selenium.webdriver:用于模拟浏览器操作并爬取JavaScript渲染的页面。例如:

from selenium import webdriver
url = 'http://www.example.com'
driver = webdriver.Chrome()
driver.get(url)
print(driver.page_source)

以上是Python爬虫中常用的一些函数及示例。需要注意的是,爬取网站时应遵守法律法规和道德规范,不得进行侵犯隐私、侵犯版权等行为。