爬虫案例(读书网)(下)

上篇链接:

CSDN-读书网https://mp.csdn.net/mp_blog/creation/editor/139306808

可以看见基本的全部信息:如(author、bookname、link.....)

写下代码如下:

python 复制代码
import requests
from bs4 import BeautifulSoup
from lxml import etree

headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'}
link="https://www.dushu.com/"
r=requests.get(link,headers=headers)
r.encoding='utf-8'

soup=BeautifulSoup(r.text,'lxml')
house_list=soup.find_all('div',class_="border books-center")
html=etree.HTML(r.text)
    # name=html.xpath('//div[@class="property-content-title"]/h3/text()')
# for house in house_list:
#     name=soup.find('div',class_="nlist").a.strong.text()
#
#     print(name)
name=html.xpath('//div[@class="bookname"]/a/text()')
author=html.xpath('//div[@class="bookauthor"]/text()')
# href=html.xpath('//div[@class="nlist"]/div/ul/li/a/@href')

#print(type(author))
for i,o in zip(name,author):
    print('<<'+i+'>>',o)

运行结果:

接下来添加link链接:

可以看见现在网站设置了反爬,我们现在通过检查浏览器能正常爬取还是有反爬:

python 复制代码
# 请用 python+selenium  爬取 XXX 网站上的所有a链接的 href属性并访问,输出访问地址和状态码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import requests

driver = webdriver.Chrome()
# 这里以百度为例
driver.get("https://www.dushu.com/")

wait = WebDriverWait(driver, 10)
links = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//a")))

# 遍历所有的链接元素,并输出href属性值
for link in links:
    href = link.get_attribute("href")
    if href.startswith("http"):
        response = requests.get(href)
        print(href, response.status_code)
    else:
        link.click()
        print(driver.current_url, driver.execute_script('return document.readyState'),
              requests.get(driver.current_url).status_code)

# 关闭浏览器
driver.quit()

运行结果:

现在可以看出是反爬。

最后我们的解析反爬,在下一篇文章详细介绍几个方法和使用效果。

相关推荐
数据知道3 分钟前
claw-code 源码分析:大型移植的测试哲学——如何用 unittest 门禁守住「诚实未完成」的口碑?
开发语言·python·ai·claude code·claw code
炸炸鱼.10 分钟前
Python 网络编程入门(简易版)
网络·python
技术小黑11 分钟前
TensorFlow学习系列10 | 数据增强
python·深度学习·tensorflow2
小堃学编程11 分钟前
【项目实战】基于protobuf的发布订阅式消息队列(2)—— 线程池
java·开发语言
万粉变现经纪人15 分钟前
如何解决 import aiohttp ModuleNotFoundError: No module named ‘aiohttp’
python·scrapy·beautifulsoup·aigc·pillow·pip·httpx
每日任务(希望进OD版)17 分钟前
线性DP、区间DP
开发语言·数据结构·c++·算法·动态规划
怨言.18 分钟前
Java内部类详解:从基础概念到实战应用(附案例)
java·开发语言
AC赳赳老秦19 分钟前
OpenClaw image-processing技能实操:批量抠图、图片尺寸调整,适配办公需求
开发语言·前端·人工智能·python·深度学习·机器学习·openclaw
XiYang-DING20 分钟前
【Java】 Java 集合框架
java·开发语言
charlie11451419121 分钟前
嵌入式C++教程实战之Linux下的单片机编程(9):HAL时钟使能 —— 不开时钟,外设就是一坨睡死的硅
linux·开发语言·c++·单片机·嵌入式硬件·c