【发布时间】:2020-06-14 14:49:55
【问题描述】:
我正在尝试使用 requests 模块在 python 中创建一个脚本,以从网站上抓取不同工作的标题。要解析不同工作的标题,我需要先从该站点获取相关响应,以便我可以使用 BeautifulSoup 处理内容。但是,当我运行以下脚本时,我可以看到该脚本生成的 gibberish 实际上不包含我要查找的标题。
website link(In case you don't see any data, make sure to refresh the page)
我试过了:
import requests
from bs4 import BeautifulSoup
link = 'https://www.alljobs.co.il/SearchResultsGuest.aspx?'
query_string = {
'page': '1',
'position': '235',
'type': '',
'city': '',
'region': ''
}
with requests.Session() as s:
s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
s.headers.update({"Referer":"https://www.alljobs.co.il/SearchResultsGuest.aspx?page=2&position=235&type=&city=®ion="})
res = s.get(link,params=query_string)
soup = BeautifulSoup(res.text,"lxml")
for item in soup.select(".job-content-top [class^='job-content-top-title'] a[title]"):
print(item.text)
我什至试过这样:
import urllib.request
from bs4 import BeautifulSoup
from urllib.parse import urlencode
link = 'https://www.alljobs.co.il/SearchResultsGuest.aspx?'
query_string = {
'page': '1',
'position': '235',
'type': '',
'city': '',
'region': ''
}
headers={
"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36",
"Referer":"https://www.alljobs.co.il/SearchResultsGuest.aspx?page=2&position=235&type=&city=®ion="
}
def get_content(url,params):
req = urllib.request.Request(f"{url}{params}",headers=headers)
res = urllib.request.urlopen(req).read()
soup = BeautifulSoup(res,"lxml")
for item in soup.select(".job-content-top [class^='job-content-top-title'] a[title]"):
yield item.text
if __name__ == '__main__':
params = urlencode(query_string)
for item in get_content(link,params):
print(item)
如何使用请求获取不同作业的标题?
PS 浏览器模拟器不是执行此任务的选项。
【问题讨论】:
-
这不是乱码,而是 Js 代码,经过缩小和混淆。恐怕您无法避免 Selenium,除非您可以对 JS 代码进行逆向工程。
-
柠檬林和杰克弗利廷似乎设法用您的代码获得了最终的 html。我会向他们询问更多详细信息,也许这与操作系统或 IP 位置有关。
标签: python python-3.x web-scraping beautifulsoup python-requests