Skip to content

关于使用"推文列表"功能没反应问题的解决办法 #27

@xANoyU

Description

@xANoyU

修改api.py中的get_timeline_screen函数
await page.wait_for_load_state("load",timeout=60000)
替换为
await page.wait_for_load_state("networkidle")

我在windows server 2022 datacenter系统 python3.11.0上测试
如果传入的height不是整数会导致playwright浏览器卡住, 也就是运行到这段代码之后不继续往下运行了
设置为整数之后就能正常获取推文列表
await page.set_viewport_size({'width': 1280, 'height': total_height})
替换为
await page.set_viewport_size({'width': 1280, 'height': int(total_height)})

但是还有一个bug, 获取的推文列表截图不完整 第五个推文只显示一部分
不知道怎么解决, 希望开发者能修一下, 还有看到这篇issues的大佬们也帮帮忙吧
解决办法如下:
在截图部分page.screenshot加上参数full_page=True

screen = await page.screenshot(
    full_page=True,
    clip={
    'x': first_bbox['x'],
     'y': first_bbox['y'],
    'width': first_bbox['width'],
    'height': total_height,
})

整体修改如下:

async def get_timeline_screen(browser: Browser,user_name: str,length: int = 5):
    url=f"{plugin_config.twitter_url}/{user_name}"
    context = await browser.new_context()
    page = await context.new_page()
    await page.goto(url,timeout=60000)
    await page.wait_for_load_state("networkidle")
    await page.wait_for_selector('.timeline-item')

    tweets = await page.query_selector_all('.timeline-item')
    first_five_tweets = tweets[:5]

    if len(first_five_tweets) > 0:
        first_bbox = await first_five_tweets[0].bounding_box()
        fifth_bbox = await first_five_tweets[4].bounding_box()
        if first_bbox and fifth_bbox:
            # 计算前五个推文所占的总高度
            total_height = fifth_bbox['y'] + fifth_bbox['height'] - first_bbox['y']

            # 有full_page所以不需要调整视口也能正常截图 注释掉
            # 调整浏览器视口的高度
            # await page.set_viewport_size({'width': 1280, 'height': int(total_height)})
            # 再次计算第一个推文的位置和尺寸,因为视口大小变化后位置可能会有所变动
            # first_bbox = await first_five_tweets[0].bounding_box()

            # 截图
            screen = await page.screenshot(
                full_page=True,
                clip={
                'x': first_bbox['x'],
                'y': first_bbox['y'],
                'width': first_bbox['width'],
                'height': total_height,
            })
            return screen
    return None

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions