selenium结合lxml爬取豆瓣电影相关信息

本文介绍了一种使用Python和Selenium爬取豆瓣电影网站数据的方法。通过PhantomJS加载整个网页,并利用XPath解析获取电影标题、排名及图片链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境说明

python3.5
centos7.2

重要代码解释

使用selenium加载网页:

driver=webdriver.PhantomJS()
driver.get("https://movie.douban.com/")

使用selenium和web进行互动将网页加在完全:

end = True
while (end):
    try:
        end = driver.find_element_by_class_name("more")
        end.click()
    except Exception as e:
        print("没有这样的text.")
        end = False

获得电影信息的web的源代码:

movis = driver.page_source
driver.close()

使用xpath解析web代码:

html = etree.HTML(movis)
titles = html.xpath("//a[@class='item']")

提取需要的内容:

i =0
while(i<len(titles)):
    url_img = titles[i].xpath("./div/img/@src")
    title_moive = titles[i].xpath("./p/text()")
    rank_movie = titles[i].xpath("./p/strong/text()")
    title_moive=re.sub("\s+","",title_moive[0])
    i= i+1

完整代码

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from scrapy.selector import Selector
from lxml import etree
import re

driver=webdriver.PhantomJS()
driver.get("https://movie.douban.com/")

end = True
while (end):
    try:
        end = driver.find_element_by_class_name("more")
        end.click()
    except Exception as e:
        print("没有这样的text.")
        end = False


movis = driver.page_source
driver.close()

print(type(movis))
html = etree.HTML(movis)
titles = html.xpath("//a[@class='item']")

i =0
while(i<len(titles)):
    url_img = titles[i].xpath("./div/img/@src")
    title_moive = titles[i].xpath("./p/text()")
    rank_movie = titles[i].xpath("./p/strong/text()")
    title_moive=re.sub("\s+","",title_moive[0])
    i= i+1
    print(url_img,"===",title_moive,"===",rank_movie)
    print("****************************************************************************")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值