爬虫所有实际的例子

1.

import requests
import re
def getHtml(url):
try:
page=requests.get(url)
page.raise_for_status()
page.encode=page.apparent_encoding
return page.text
except:
return ‘产生异常’

def getImage(html):
global x
base=‘https://www.50zw.com/files/’
matcher=re.findall(r’article/image.*?jpg’,html)
for i in matcher:
print(base+i)
response=requests.get(base+i)
with open(‘image/%s.jpg’%x,‘wb’) as f:
f.write(response.content)
x=x+1

x=0
for i in [1,2,3]:
url=‘https://m.50zw.com/wapsort/1_’+str(i)+’.html’
html=getHtml(url)
getImage(html)

2

import requests
import re
from bs4 import BeautifulSoup
def getHtml(url):
try:
page=requests.get(url)
page.raise_for_status()
page.encoding=page.apparent_encoding
return page.text
except:
print(“error”)

def getImage(html):
soup=BeautifulSoup(html,“html.parser”)
tags=soup.find_all(name=“img”)
print(len(tags))
for tag in tags:
print(tag[‘src’])
response=requests.get(tag[‘src’])
with open("") as f:
12313

url=“https://m.50zw.com/wapsort/1_1.html”
html=getHtml(url)
getImage(html)

3

import requests
import re
import pandas as pd
from bs4 import BeautifulSoup
def getHtml(url):
try:
page=requests.get(url)
page.raise_for_status()
page.encoding=page.apparent_encoding
return page.text
except:
print(“error”)

def getInformation(html):
soup=BeautifulSoup(html,“html.parser”)
tags=soup.select(‘div.article’)
names=[]
writers=[]
counts=[]

for tag in tags:
    name=tag.select('a')[0].string
    writer=tag.select('span.mr15')[0].string
    count=tag.select('span.count')[0].string
    describe=tag.select('span')[-1].string
    names.append(name)
    writers.append(writer)
    counts.append(count)
    #s=name + '  ' + writer + '  ' + count + '\n'
p=pd.DataFrame({"name":names,"writer":writers,"counts":counts})
print(p)
p.to_csv("123.csv")

url=“https://m.50zw.com/wapsort/1_1.html”
html=getHtml(url)
getInformation(html)

4

BeautifulSoup是一个用于解析HTML和XML文档的Python库。利用BeautifulSoup,我们可以方便地从网页中提取出需要的信息。 以下是一个使用BeautifulSoup进行爬虫例子: ```python import requests from bs4 import BeautifulSoup # 发起HTTP请求,获取网页内容 response = requests.get('https://example.com') # 将网页内容解析为BeautifulSoup对象 soup = BeautifulSoup(response.text, 'html.parser') # 找到网页中所有的<a>标签 a_tags = soup.find_all('a') # 遍历所有<a>标签,提取其中的链接和文本 for a_tag in a_tags: link = a_tag['href'] text = a_tag.get_text() print(f"链接:{link},文本:{text}") # 找到网页中所有的<img>标签 img_tags = soup.find_all('img') # 遍历所有<img>标签,提取其中的图片链接和alt文本 for img_tag in img_tags: src = img_tag['src'] alt = img_tag.get('alt', '未命名') print(f"图片链接:{src},alt文本:{alt}") ``` 以上代码示例中,我们首先使用requests库发送一个HTTP请求,获取到网页的内容。然后,利用BeautifulSoup的`find_all`方法,我们找到了网页中的所有<a>标签和<img>标签,然后提取了其中的链接、文本、图片链接和alt文本。 实际应用中,我们可以进一步对提取到的内容进行处理,例如保存图片到本地、将提取的数据存储到数据库或者进行进一步的分析。BeautifulSoup是一个功能强大、易于使用的库,它在Python爬虫开发中有着广泛的应用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值