web抓取-点击ajax调用,然后抓取页面(可以在python中完成)


webscraping - clicking an ajax call then scraping page (can do it in python)

我在python中有一些代码,它抓取一个页面,找到所有类名为"group head"的元素,然后单击它们生成一个执行了所有ajax调用的页面。这在python中有效,但我想知道它是否可以在curl/php编码上完成?

 # Get scraping...
tree = parseLxml(driver=driver, url=url) # Go to URL and parse
elem = driver.find_elements_by_class_name('group-head') # Use ChromeDriver to find element to get to the Ajax call
for x in range(0,len(elem)): # Loop through all such elements
    try:  
        time.sleep(0.5)
        elem[x].click() # Click the element
        time.sleep(1.5) # Too fast and errors can occur, so wait...
    except:
        pass
newpage = driver.page_source # Need to get page source again now all visible
newtree = html.fromstring(newpage)
match = newtree.xpath('//td[contains(@class,"score-time")]/a/@href') # Scrape match link
base = 'http://uk.soccerway.com'
for m in match:
    mURL = base+str(m)
    print ('Match URL:',mURL)

您的代码正在使用ChromeDriver,因此您应该查找PHP绑定。

看看https://github.com/facebook/php-webdriver,您应该能够以相同的方式使用它。代码未经过测试,但应该看起来像:

$host = 'http://localhost:4444/wd/hub'; // Selenium Host
$driver = ChromeDriver::create($host);
$driver->get($url); // Got to Url and Load Page
$elements = $driver->findElements(WebDriverBy::className('group-head'));
....

是的,使用PHP是可能的:)

但你必须遵循以下步骤。。

1) 从这里下载PHP 的Dom解析器

2) 在单击页面中的链接时,可以使用ajax调用该链接,从而获取文件(file_get_html)的内容。

3) 最后使用它的id、元素、类名来获取所需的数据。

$html = file_get_html('http://www.google.com/');
// Find all images 
foreach($html->find('img') as $element) 
       echo $element->src . '<br>';
// Find all links 
foreach($html->find('a') as $element) 
       echo $element->href . '<br>';