最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】pyppeteer如何给输入框中输入文字

输入框 crifan 4075浏览 0评论
折腾:
【未解决】pyppeteer中如何定位查找百度搜索输入框
期间,继续试试,给输入框中输入文字
pyppeteer input text
javascript – How to fill an input field using Puppeteer? – Stack Overflow
javascript – Puppeteer write in input field – Stack Overflow
javascript – How to type a text in input box in puppeteer – Stack Overflow
好像是用type 表示input输入?
API Reference — Pyppeteer 0.0.25 documentation
awaitpage.keyboard.type('Hello, World!')
awaitpage.keyboard.press('ArrowLeft')

awaitpage.keyboard.down('Shift')
都是keyboard的
javascript – How to type a text in input box in puppeteer – Stack Overflow
await page.type('input[name=pickupAgingComment]', 'test comment', {delay: 20})
好像是:只有针对于page级别的type去输入?
没有针对 已找到的元素 去操作的?
How to set Value for a Input Element · Issue #441 · puppeteer/puppeteer · GitHub
puppeteer的逻辑是:
await page.focus('#lst-ib')
page.keyboard.type('China')
先focus,再type
另外:
    await page.evaluate((a, b) => {
      document.querySelector('#a').value = a;
      document.querySelector('#b').value = b;
      document.querySelector('#c').click();
    }, a, b);
node.js – Input text while running puppeteer – Stack Overflow
javascript – How to delete existing text from input using Puppeteer? – Stack Overflow
去找找是否有:
对于前面xpath找到的 元素
<coroutine object Page.xpath at 0x10f15cdb0>
去操作的
https://miyakogi.github.io/pyppeteer/reference.html#pyppeteer.page.Page.xpath
“coroutine xpath(expression: str) → List[pyppeteer.element_handle.ElementHandle][source]
Evaluate the XPath expression.
If there are no such elements in this page, return an empty list.
Parameters:
expression (str) – XPath string to be evaluated.

pyppeteer input text
pyppeteer.input — Pyppeteer 0.0.25 documentation
How to fill &lt;input&gt; field using pyppeteer – TechOverflow
content = "My content" # This will be filled into <input id="myinput"> !
await page.evaluate(f"""() => {{
    document.getElementById('myinput').value = '{content}';
}}""")
这么麻烦?
算了,先去试试:
    page.focus(SearchInputXpath)
    searchStr = "crifan"
    page.keyboard.type(searchStr)
结果:
有警告:
/Users/crifan/dev/dev_root/python/puppeteerBaiduSearch/puppeteerBaiduSearch.py:18: RuntimeWarning: coroutine 'Page.focus' was never awaited
  page.focus(SearchInputXpath)
换成:
await page.focus(SearchInputXpath)
结果:
发生异常: ElementHandleError
Evaluation failed: DOMException: Failed to execute 'querySelector' on 'Document': '//input[@id='kw']' is not a valid selector.
看来不支持xpath
要去换成selector
API Reference — Pyppeteer 0.0.25 documentation
直接去试试click
    SearchInputXpath = "//input[@id='kw']"
    searchInputElem = page.xpath(SearchInputXpath)
    print("searchInputElem=%s" % searchInputElem)
    searchInputElem.click()
结果:
发生异常: AttributeError
'coroutine' object has no attribute 'click'
Pyppeteer 使用笔记 – 拐弯 – 博客园
# 打印当前页标题
print(await page.title())


# 抓取新闻内容  可以使用 xpath 表达式
"""
# Pyppeteer 三种解析方式
Page.querySelector()  # 选择器
Page.querySelectorAll()
Page.xpath()  # xpath  表达式
# 简写方式为:
Page.J(), Page.JJ(), and Page.Jx()
"""
element = await page.querySelector(".feed-infinite-wrapper > ul>li")  # 纸抓取一个
print(element)
# 获取所有文本内容  执行 js
content = await page.evaluate('(element) => element.textContent', element)
print(content)
打算换用:
searchInputElem = await page.querySelector("")
但是要去搞清楚
如何写css的selector
css selector 语法
CSS 选择器 – CSS(层叠样式表) | MDN
CSS 选择器 | 菜鸟教程
CSS 选择器参考手册
https://www.w3school.com.cn/cssref/css_selectors.asp
对于元素:
<input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">
感觉是:
input[id=kw]
试试
    searchInputElem = await page.querySelector("input[id=kw]")
    print("searchInputElem=%s" % searchInputElem)
    searchInputElem.click()
结果
好像是能找到元素?
searchInputElem.click()
运行后,至少没报错。
不过后续的:
    searchStr = "crifan"
    page.keyboard.type(searchStr)
并没有输入内容:
好像
javascript – How to type a text in input box in puppeteer – Stack Overflow
await page.type('input[name=pickupAgingComment]', 'test comment', {delay: 20})
是可以的?
去试试
写了:
    searchStr = "crifan"
    page.type("input[id=kw]", searchStr, delay=20)
然后发现:
page.type
可以查看源码
/Users/crifan/.pyenv/versions/3.6.6/lib/python3.6/site-packages/pyppeteer/page.py
    async def type(self, selector: str, text: str, options: dict = None,
                   **kwargs: Any) -> None:
        """Type ``text`` on the element which matches ``selector``.


        If no element matched the ``selector``, raise ``PageError``.


        Details see :meth:`pyppeteer.input.Keyboard.type`.
        """
        frame = self.mainFrame
        if not frame:
            raise PageError('no main frame.')
        return await frame.type(selector, text, options, **kwargs)
运行有警告:
/Users/crifan/dev/dev_root/python/puppeteerBaiduSearch/puppeteerBaiduSearch.py:22: RuntimeWarning: coroutine 'Page.type' was never awaited
  page.type("input[id=kw]", searchStr, delay=20)
去加上:await
await page.type("input[id=kw]", searchStr, delay=20)
结果:
终于可以输入了。
javascript – How to fill an input field using Puppeteer? – Stack Overflow
后来发现:
await page.focus('#email')
await page.keyboard.type('test54')
也是可以的。
【总结】
此处对于元素:
<input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">
想要输入文字,则:
(方式1)
无需,也没法,定位元素,再输入
而是:直接定位并输入
定位此处只适合用:Selector
此处Selector写法是:
"input[id='kw']"
然后输入是用type函数。
完整代码是:
searchStr = "crifan"
SearchInputSelector = "input[id='kw']"

await page.type(SearchInputSelector, searchStr, delay=20)
即可。
(方式2)先(通过selector)focus,再(用keyboard)type
代码:
    searchStr = "crifan"
    SearchInputSelector = "input[id='kw']"

    await page.focus(SearchInputSelector)
    await page.keyboard.type(searchStr)
(方式3)更复杂的:
先selector
在click(类似于focus)
再用keyboard输入type
代码是:
searchStr = "crifan"
SearchInputSelector = "input[id='kw']"

searchInputElem = await page.querySelector(SearchInputSelector)
await searchInputElem.click()
await page.keyboard.type(searchStr)
即可。
注意:一定要加await,否则:代码运行无效果。且还会报警告:
/Users/crifan/dev/dev_root/python/puppeteerBaiduSearch/puppeteerBaiduSearch.py:18: RuntimeWarning: coroutine 'ElementHandle.click' was never awaited
  searchInputElem.click()
相关文档
coroutine type(selector: str, text: str, options: dict = None, **kwargs) → None[source]  API Reference — Pyppeteer 0.0.25 documentation
https://miyakogi.github.io/pyppeteer/reference.html#pyppeteer.page.Page.type

转载请注明:在路上 » 【已解决】pyppeteer如何给输入框中输入文字

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
80 queries in 0.191 seconds, using 22.11MB memory