使用Goutte进行解析 - 如何在包含文本字符串

时间:2017-08-21 11:41:52

标签: php parsing goutte domcrawler

我正在使用https://github.com/FriendsOfPHP/Goutte来解析和提取数据,而且我做得很好......

但现在我偶然发现了一个稍微不友好的地方:

<tr>
<th>Website:</th>
<td>
    <a href="http://www.adres.com" target="_blank">http://www.adres.com</a>
</td>
</tr>

我正在尝试从td元素中获取文本,该元素紧跟在th元素后面,该元素包含特定字符串{@ 1}}。

我的php看起来像这样:

Website:

问题

我的代码不起作用。

我的尝试
  • 我尝试同时使用$client3 = new \Goutte\Client(); $crawler3 = $client3->request('GET', $supplierurl . 'contactinfo.html'); if($crawler3->filter('th:contains("+Website+") + td a')->count() > 0) { $parsed_company_website_url = $crawler3->filter('th:contains("Website:") + td')->text(); } else { $parsed_company_website_url = null; } return $parsed_company_website_url; "+Website+"
  • 我尝试通过计算表格的行来进行一些智能定位,但目标网站上的每个数据库条目都以不同的方式排列项目,没有可靠的模式。

待办事项

使脚本从

中提取文本

2 个答案:

答案 0 :(得分:0)

似乎contains()是一个jquery功能而不是css选择器。使用css,您可以检查属性值,但不检查标记内的文本节点。

所以,在你的情况下,我会使用xpath选择器,尤其是:following-sibling(参见https://stackoverflow.com/a/29380551/1997849

答案 1 :(得分:0)

这是您问题的解决方案。

php_notes.php文件中的表。

import requests, random, re
from bs4 import BeautifulSoup as bs

url = "https://www.thenational.ae/search?q=aramco"
webpage = requests.get(url)
soup = bs(webpage.text, "html.parser")
for link in soup.find_all('h1'):
    print(link.get('href'))

Crawler.php从php_notes.php文件的锚标记中找到文本。

<table id="table" border="1">
    <tr>
    <a href="">xyz</a>
    <a href="">abc</a>
    <h1>Heading</h1>
    <th>Website:</th>
    <td>
        <a href="http://www.adres.com" target="_blank">http://www.adres.com</a>
    </td>
    <th>Website:abc</th>
    <td>
        <a href="http://www.adres.com" target="_blank">http://www.ares.com</a>
    </td>
    </tr>
</table>

您可以从“ https://symfony.com/doc/current/components/dom_crawler.html”获得有关Symfony Crawler的帮助