requests_html中通过类名获取元素(Get Element By Class)失效问题求助
Hey Alp, let's dig into why your code isn't pulling the elements you're targeting!
First off, the big issue here is your CSS selector syntax. When you use .current-text ng-tns-c186-9, that's telling the parser to look for elements with the class ng-tns-c186-9 that are children of elements with the class current-text—but both are class names for the same element, right? To select an element that has both classes, you need to chain them together with dots, no spaces: .current-text.ng-tns-c186-9.
That said, there are a couple more things to check since this is a dynamically loaded site:
- The
ng-tns-c186-9class looks like an auto-generated Angular class, which might change every time you load the page. Relying on these unstable class names is risky—you might want to stick to just.current-textfirst, see if that returns any elements, then narrow things down from there. - Your
render()parameters might need tweaking. Try increasing thesleeptime to 2 or 3 seconds, and maybe bumpscrolldownto 2, to make sure the page fully loads all dynamic content before you try to scrape it.
Here's a revised version of your code to test:
from requests_html import HTMLSession session2 = HTMLSession() rghtml = session2.get('https://www.biletix.com/etkinlik-grup/382508946/TURKIYE/tr') # Give the page more time to load and scroll a bit further rghtml.html.render(sleep=2, keep_page=True, scrolldown=2) # Fixed selector for elements with both classes, or just use .current-text if the dynamic class changes results = rghtml.html.find('.current-text.ng-tns-c186-9') # Loop through results to print their actual text content for result in results: print(result.text) print('ok')
If you still get an empty list after fixing the selector, try printing out rghtml.html.html (the full page source after rendering) and search for "current-text" to confirm the elements are actually present when you scrape. That'll help you rule out if the content is loaded even later, or if you need a different targeting method entirely.
备注:内容来源于stack exchange,提问作者Alp Eren Gül

