python 截长图,解决高度限制问题
class TBao(object):
def __init__(self, is_mobile=False):
self.browser = None # 浏览器对象
self.page = None # 页对象
self.is_mobile = is_mobile
async def init(self, headless=False):
"""
初始化
:return:
"""
self.browser = await launch({
# 'slowMo': 100, # 放慢速度
'headless': headless,
'args': ['-no-sandbox', '--disable-infobars'],
'userDataDir': fr"E:\temporary",
})
self.page = await self.browser.newPage()
if self.is_mobile:
ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) ' \
'AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
width, height = 375, 812
else:
ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit' \
'/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'
width, height = screen_size()
await self.page.setUserAgent(ua)
await self.page.setViewport(viewport={"width": width, "height": height, "isMobile": True})
async def home_screenshot(self, url, name):
"""
淘宝h5页面截图
:param url: 淘宝app分享出来的首页链接
:param name: 店铺名称
:return:
"""
# page = await self.browser.newPage()
await self.page.evaluateOnNewDocument('''() => {
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
}
''')
await self.page.setJavaScriptEnabled(enabled=True)
# 设置当前页面UA
await self.page.setUserAgent(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/76.0.3809.132 Safari/537.36"
)
# 打开路由
await self.page.goto(url)
await asyncio.sleep(3)
for i in range(10):
try:
offsetWidth = await self.page.evaluate("""
() => {
return {
width: document.body.offsetWidth
}
}
""")
except:
await asyncio.sleep(10)
# 设置页面视图大小
await self.page.setViewport(viewport={'width': offsetWidth["width"], 'height': 955})
await asyncio.sleep(3)
for i in range(10):
try:
'''修改页面高度'''
await self.page.evaluate("""
function change(){
var inp = document.getElementsByClassName('rax-scrollview'); // 寻找修改高度的元素
inp[0].style = "overflow: visible;";
}
""")
except:
await asyncio.sleep(10)
print("页面标题", await self.page.title())
print("准备滚动")
await asyncio.sleep(0.5)
for i in range(95):
await self.slider(page=self.page)
await asyncio.sleep(3)
# 截图
# await page.screenshot({'path': 'test.png', 'type': 'png', 'fullPage': True, 'omitBackground': True})
await self.page.screenshot({'path': f'./imgs/{name}.jpeg', 'type': 'jpeg', 'fullPage': True})
print("截图完成")
await asyncio.sleep(15)