使用Python擦除javascript生成的页面

Scraping a javascript generated page using Python

本文关键字:Python 擦除 javascript 使用      更新时间:2023-10-12

我需要为https://hasjob.co/,我可以像往常一样通过登录页面和抓取来抓取一些信息,但大多数信息都是由Javascript生成的,只有当你向下滚动到页面底部时。

有使用python的解决方案吗??

import mechanize
import cookielib
from bs4 import BeautifulSoup
import html2text
import pprint
job = []
# Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Chrome')]
# The site we will navigate into, handling it's session
br.open('https://auth.hasgeek.com/login')
# View available forms
##for f in br.forms():
##    print f
# Select the second (index one) form (the first form is a search query box)
br.select_form(nr=1)
# User credentials
br.form['username'] = 'username'
br.form['password'] = 'pass'
br.submit()
##print(br.open('https://hasjob.co/').read())
r = br.open('https://hasjob.co/')

soup = BeautifulSoup(r)

for tag in soup.find_all('span',attrs={'class':'annotation bottom-right'}):
    p = tag.text
    job.append(p)

pp = pprint.PrettyPrinter(depth=6)
pp.pprint(job)
由于某些原因,几乎没有人注意到Hasjob有Atom提要,并且它是从主页链接的。使用feedparser库从Hasjob读取结构化数据非常简单:
import feedparser
feed = feedparser.parse('https://hasjob.co/feed')
for job in feed.entries:
    print job.title, job.link, job.published, job.content

订阅源过去是满30天的,但现在已经有800多个条目,服务器上也有相当多的负载,所以我把它减少到了最后24小时的工作。如果你想要定期帮助工作,只需每天至少从这个URL加载一次。

您可以看看python模块PyV8,它是Google V8 javascript引擎的python包装器。

您也可以尝试通过selenium使用ghostdriver,请参阅此处的示例:在Windows上的Python中使用selenium with ghostdriver。使用selenium,您可以选择在工作时在Firefox或Chrome中运行可视化浏览器实例(通过chromedriver),然后在scraper工作时切换到PhantomJS(无窗口浏览器)。不过,请注意,创建一个完整的浏览器实例可能完全是小题大做,尽管这实际上取决于你在做什么。如果你不经常运行它,我想这很好,但通常硒用于浏览器测试,而不是刮擦。