Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to select element in drop-down list #566

Open
Su-Da-Ko opened this issue Jan 22, 2024 · 1 comment
Open

How to select element in drop-down list #566

Su-Da-Ko opened this issue Jan 22, 2024 · 1 comment

Comments

@Su-Da-Ko
Copy link

I want to select element in drop-down list, like "Select" method in Selenium, but only get result before select.
How I modify code below?
(Run in google colab)

from requests_html import AsyncHTMLSession
url = "https://hoge.com"

session = AsyncHTMLSession()
r = await session.get(url)
await r.html.arender(timeout=60, keep_page=True)

select = r.html.find("select")
if len(select) > 0:
    print(select[0])  // <Element 'select' ... >

option = r.html.find("option")
print(option)  // [<Element 'option' value='1' selected='selected'>, <Element 'option' value='1'>, <Element 'option' value='2'>, ... ]

f = await r.html.page.select('select', "3")
print(f)  // ["3"]

option = r.html.find("option")
print(option)  // [<Element 'option' value='1' selected='selected'>, <Element 'option' value='1'>, <Element 'option' value='2'>, ... ]
@Ishmeet1027
Copy link

from requests_html import AsyncHTMLSession

url = "https://hoge.com"

async def main():
session = AsyncHTMLSession()
r = await session.get(url)
await r.html.arender(timeout=60, keep_page=True)

# Find the select element
select = r.html.find("select")
if len(select) > 0:
    print(select[0])  # <Element 'select' ... >

    # Extract all options from the select element
    options = select[0].find("option")
    print("Available options:")
    for i, option in enumerate(options):
        value = option.attrs.get("value", "")
        text = option.text
        is_selected = "selected" in option.attrs
        print(f"Option {i + 1}: Value='{value}', Text='{text}', Selected={is_selected}")

    # Simulate selecting an option (e.g., the option with value "3")
    simulated_value = "3"
    selected_option = next((opt for opt in options if opt.attrs.get("value") == simulated_value), None)
    if selected_option:
        print(f"Simulated selection: Value='{simulated_value}', Text='{selected_option.text}'")
    else:
        print(f"No option with value='{simulated_value}' found.")
else:
    print("No <select> element found.")

Run the main function

await main()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants