| 
 
 ?在使用 symfony 中。有需求需要对页面元素进行 爬虫。 一开始 计划其他办法。 但是 好在symfony有官方 爬虫组件。 索性看文档 直接 就可以使用。?  
 $url = $this->baseUrl . $list->getApiUrL();
        $response = file_get_contents($url);
        $crawler = new Crawler();
        $crawler->addHtmlContent($response);
        $data = [];
        try {
            //使用crawler进行页面内容分析
            $content = $crawler->filterXPath('//ul[contains(@class,"conte_heliu_ul")]')->text();
            $imgSrc = $crawler->filterXpath('//img')->extract(array('src'));
            $name = $crawler->filterXPath('//ul[contains(@class,"conte_heliu_ul")]/li')->each(function (Crawler $node, $i) use (&$data) {
                $item = $node->filterXPath('//div/span')->text();
                $city = $node->filterXPath('//span')->text();
                return $city . '-' . $item;
            });
            $userName = implode(',', $name);
            $imgUrl = str_replace('../', '', $imgSrc[0]);
            $url = str_replace('3g/', '', $this->baseUrl);
            $fileUrl = '';
            if (!empty($imgUrl)) {
                $fileUrl = $url . $imgUrl;
            }
            $data = [
                'content' => $content,
                'userName' => $userName,
                'img' => $fileUrl,
            ];
        } catch (Exception $e) {
            $output->writeln('error ');
        }  
use Symfony\Component\DomCrawler\Crawler;
function run()
{
? ? //伪造浏览器UA
? ? $headers = [
? ? ? ? 'user-agent' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
? ? ];
? ? $client = new Client([
? ? ? ? 'timeout' => 20,
? ? ? ? 'headers' => $headers
? ? ]);
? ? //发送请求获取页面内容
? ? $response = $client->request('GET', $url)->getBody()->getContents();
? ? $data = [];
? ? $crawler = new Crawler();
? ? $crawler->addHtmlContent($response);
? ? //使用crawler进行页面内容分析
? ? try{
? ? ? ? //这里使用的是xpath语法,轮询forFlow子类day中的元素,既页面上每一篇文章的块状元素,并且进行内容获取
? ? ? ? $crawler->filterXPath('//div[contains(@class, "forFlow")]/div[contains(@class, "day")]')->each(function(Crawler $node, $i) use (&$data){
? ? ? ? ? ? $item = [
? ? ? ? ? ? ? ? 'date' => $node->filterXPath('//div[contains(@class, "dayTitle")]/a')->text(),
? ? ? ? ? ? ? ? 'title' => $node->filterXPath('//div[contains(@class, "postTitle")]/a')->text(),
? ? ? ? ? ? ? ? 'abstract' => $node->filterXPath('//div[contains(@class, "postCon")]/div')->text(),
? ? ? ? ? ? ? ? 'url' => $node->filterXPath('//div[contains(@class, "postCon")]/div/a')->attr('href'),
? ? ? ? ? ? ];
? ? ? ? ? ? $data[] = $item;
? ? ? ? });
? ? }catch (\Exception $e){
? ? ? ? echo $e->getMessage() . PHP_EOL;
? ? }
? ? //打印结果
? ? print_r($data);
}  
                
        
        
    
  
 
 |