Web scraping 使用BeautifulSoup创建木材行业数据库
我想用BeautifulSoup从锯木厂老板(在“Owned by:”之后)那里刮掉Web scraping 使用BeautifulSoup创建木材行业数据库,web-scraping,beautifulsoup,Web Scraping,Beautifulsoup,我想用BeautifulSoup从锯木厂老板(在“Owned by:”之后)那里刮掉 <td> <a href="../company.php?id=729">AKD Softwoods </a> </td> 我试着去适应,但我不明白为什么它不起作用 <td> <a href="../company.php?id=729">AKD Softwoods </a> </td> 我用正则表达
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
我试着去适应,但我不明白为什么它不起作用
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
我用正则表达式来帮助我找到你要找的元素
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
代码:
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
输出:
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
AKD Softwoods
AKD Softwoods
为了解决您提交的代码问题,您未成功的原因是,如果td.text==“Owned by”作为您的条件,则使用
。虽然这似乎可行,但它永远不会返回您想要的内容,因为您正在清理的网站将锯木厂所有者放在所有者之后:“
”。(如果需要,您将看到
标记的所有者为:)
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
虽然由“拥有的”和由“
拥有的”之间的差异似乎可以忽略不计,但它对您的程序产生了巨大的影响。如果td.text==“所有者:”:
,只需将代码更改为,您将得到正确的响应:
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
import requests
from bs4 import BeautifulSoup
page = requests.get('https://www.sawmilldatabase.com/sawmill.php?id=1282')
soup = BeautifulSoup(page.text, 'html.parser')
lst = soup.find_all('td')
for td in lst:
if td.text == "Owned by: ":
print("yes")
print(lst[lst.index(td)+1].text)
或者,如果td.text:
中的“Owned by”,您也可以使用,作为您的条件,但这并不完全理想,如果有另一个
标记包含该信息
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
希望有帮助
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
编辑
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
哦,在lst=soup中也不要大写TD
。查找所有('TD')
下面的方法怎么样!!如果您遵守此用法如果sth.text==“sth other:”
,主要问题是倒逗号内的文本必须与网页中存储的文本相同。如果您碰巧使用了If sth.text==“sth other:”
这个,它将不再工作,因为它最后一部分的额外空间已被占用。请尝试以下方法:
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
import requests
from bs4 import BeautifulSoup
soup = BeautifulSoup(requests.get("https://www.sawmilldatabase.com/sawmill.php?id=1282").text,"lxml")
for items in soup.select("table td"):
if "Owned by:" in items.text:
name = items.find_next_sibling().text
print(name)
输出:
<td>
<a href="../company.php?id=729">AKD Softwoods </a>
</td>
AKD Softwoods
AKD Softwoods