Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 与BeautifulSoup.find混淆?_Python_Html_Web Scraping_Beautifulsoup - Fatal编程技术网

Python 与BeautifulSoup.find混淆?

Python 与BeautifulSoup.find混淆?,python,html,web-scraping,beautifulsoup,Python,Html,Web Scraping,Beautifulsoup,我正试图获取某一律师事务所的律师所就读的大学,但我不确定如何获取此链接中列出的两所大学:。如第一幅链接图片所示,这位律师就读的两所大学都有两个独立的“李”标签 当我运行以下代码时,我只得到第一个'li'标记末尾的html(如第二个链接图像所示),而不是第二个li部分,因此我只得到第一所大学“Carleton学院”: 基站仅获取第一个li元素。我不知道为什么。如果您想尝试使用lxml,这里有一种方法 import lxml from lxml import html url = 'https

我正试图获取某一律师事务所的律师所就读的大学,但我不确定如何获取此链接中列出的两所大学:。如第一幅链接图片所示,这位律师就读的两所大学都有两个独立的“李”标签

当我运行以下代码时,我只得到第一个'li'标记末尾的html(如第二个链接图像所示),而不是第二个li部分,因此我只得到第一所大学“Carleton学院”:


基站仅获取第一个li元素。我不知道为什么。如果您想尝试使用lxml,这里有一种方法

import lxml
from lxml import html


url = 'https://www.wlrk.com/attorney/hahn/'
res = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0'})

tree = html.fromstring(res.content)
education = tree.xpath("//div[@class='attorney--education']//li/a/text()")

print(education)
输出:

[“卡尔顿学院”、“纽约大学法学院”]


更改您的解析器,我将使用
选择
并直接针对
a
元素lxml’更宽容,可以处理不应该出现的杂散关闭
a
标签。另外,
find
将只返回第一个匹配项,而
find\u all
将返回所有匹配项

e、 g

杂散端标签a

来自第231行第127列;至第231行第130列

ollege,2013

杂散端标签a

来自第231行第239列;至第231行第242列

法律法典,J.D.


不确定为什么bs同时获取两个li元素。我使用lxml使其正常工作。select()函数是否知道“律师--教育”是div标记的一部分?我不明白为什么不必在选择器中输入div。此外,这也很有效,谢谢您的帮助。您可以在中添加div。较短的选择器通常更好,类选择器比tag+class更快。我检查了页面,发现我不需要指定标记(div),类也足以获取父元素。它更快。
import lxml
from lxml import html


url = 'https://www.wlrk.com/attorney/hahn/'
res = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0'})

tree = html.fromstring(res.content)
education = tree.xpath("//div[@class='attorney--education']//li/a/text()")

print(education)
import requests
from bs4 import BeautifulSoup as soup

url = 'https://www.wlrk.com/attorney/hahn/'
res = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0'})
personal_soup = soup(res.content, "lxml")    
educations = [a.text for a in personal_soup.select('.attorney--education a')]
print(educations)