Python爬虫中phantomJS+beautifulsoup无法获取特定网页内容,应该用什么方法?
网页如下: https://www.joinquant.com/post/2997?f=sharelist&m=list
特定的内容:当前持仓和最新下单
我只想做一个发现更新就发邮件通知我的小程序,现在不知道怎样爬里面的内容。。。
Python爬虫中phantomJS+beautifulsoup无法获取特定网页内容,应该用什么方法?
直接爬接口,当前持仓: https://www.joinquant.com/algorithm/live/sharePosition?isAjax=1&backtestId=f2c44b7ca48dafa4c2461125700ec8b0&date=2017-04-07&isMobile=0&isForward=1&ajax=1 ,最新下单: https://www.joinquant.com/algorithm/live/shareTransaction?isAjax=1&backtestId=f2c44b7ca48dafa4c2461125700ec8b0&date=2017-04-07&isMobile=0&isForward=1&ajax=1
遇到这种问题,先别急着换工具链。PhantomJS现在维护状态不佳,很多动态渲染的页面用老版本确实抓不到。我通常的做法是直接上 Selenium + ChromeDriver,配合 BeautifulSoup 做解析,稳定又省心。
下面给你个能直接跑的完整例子,目标是用动态渲染的方式获取页面内容:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time
# 设置Chrome为无头模式,不显示浏览器窗口
chrome_options = Options()
chrome_options.add_argument('--headless') # 无头模式
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')
# 启动浏览器
driver = webdriver.Chrome(options=chrome_options)
try:
# 访问目标网页
url = "https://example.com" # 替换成你的目标网址
driver.get(url)
# 等待页面加载完成,可以根据需要调整等待时间或使用显式等待
time.sleep(3) # 简单等待3秒,复杂页面可能需要更长时间
# 获取渲染后的页面源码
page_source = driver.page_source
# 用BeautifulSoup解析
soup = BeautifulSoup(page_source, 'html.parser')
# 这里写你的提取逻辑,比如找某个class的元素
# target_elements = soup.find_all('div', class_='your-target-class')
# for element in target_elements:
# print(element.text)
# 示例:打印页面标题
print("页面标题:", soup.title.string if soup.title else "无标题")
finally:
# 记得关闭浏览器
driver.quit()
几个关键点:
- 确保安装了
selenium包 (pip install selenium) - 去 https://chromedriver.chromium.org/ 下载对应Chrome版本的驱动,放在PATH里
- 如果页面加载慢,可以把
time.sleep(3)换成Selenium的显式等待(WebDriverWait) - 遇到反爬就加些常规header,或者用
chrome_options.add_argument('--user-agent=xxx')改UA
简单总结: 换Selenium+ChromeDriver这套现代方案,动态页面基本通吃。
请问用什么方法找出来的啊?厉害啊~~
看接口请求呗。 network 里。 讲道理 看生成 html 爬取的是知乎教程的水平
我也有这个问题。。 有些页面是 js 动态加载的,我用 phantomJS 的 webdriver 访问它,但是有些 class = "flag xxxx xxxx "不能用 find_element_by_class_name()获取。因为这个 class 中有空格。。🤔🤔
不知道怎么直接向网站发出 获取 js 加载内容的请求,有 v 友简单说下方法吗
有空格是因为它有多个 class ,我没用过 phantomJS 不清楚它是怎么筛选多个 class 的,如果是 jQuery 的活就将多个 class 用英文的点"."串联起来
动态加载最好还是分析 ajax 接口,找到规律,然后进行请求
多谢,明天去试试 嘿嘿🤓🤓
我去搜一下然后试试吧,谢谢

