이 xpath 표현식을 BeautifulSoup으로 어떻게 번역 할 수 있습니까?
-
06-07-2019 - |
문제
a에 대한 대답 이전 질문, 여러 사람들이 내가 사용한다고 제안했습니다 BeautifulSoup 내 프로젝트를 위해. 나는 그들의 문서로 어려움을 겪고 있었고 그것을 구문 분석 할 수는 없습니다. 누군가 내가이 표현을 아름다운 표현식으로 번역 할 수있는 섹션을 가리킬 수 있습니까?
hxs.select('//td[@class="altRow"][2]/a/@href').re('/.a\w+')
위의 표현은 스크레이프. Regex를 적용하려고합니다 re('\.a\w+')
에게 td class altRow
거기에서 링크를 얻기 위해.
또한 다른 튜토리얼이나 문서에 대한 포인터에 감사드립니다. 나는 아무것도 찾을 수 없었다.
당신의 도움을 주셔서 감사합니다.
편집하다:나는 이것을보고있다 페이지:
>>> soup.head.title
<title>White & Case LLP - Lawyers</title>
>>> soup.find(href=re.compile("/cabel"))
>>> soup.find(href=re.compile("/diversity"))
<a href="/diversity/committee">Committee</a>
그러나 페이지 소스를 보면 "/cabel"
거기에 있습니까 :
<td class="altRow" valign="middle" width="34%">
<a href='/cabel'>Abel, Christian</a>
어떤 이유로, 검색 결과는 BeautifulSoup으로 보이지 않지만 XPath에 보입니다. hxs.select('//td[@class="altRow"][2]/a/@href').re('/.a\w+')
"/cabel"잡기
편집하다:코발 : 아직 작동하지 않습니다. 그러나 내가 이것을 검색 할 때 :
>>>soup.findAll(href=re.compile(r'/.a\w+'))
[<link href="/FCWSite/Include/styles/main.css" rel="stylesheet" type="text/css" />, <link rel="shortcut icon" type="image/ico" href="/FCWSite/Include/main_favicon.ico" />, <a href="/careers/northamerica">North America</a>, <a href="/careers/middleeastafrica">Middle East Africa</a>, <a href="/careers/europe">Europe</a>, <a href="/careers/latinamerica">Latin America</a>, <a href="/careers/asia">Asia</a>, <a href="/diversity/manager">Diversity Director</a>]
>>>
그것은 모든 링크를 두 번째 문자 "a"로 반환하지만 변호사 이름은 아닙니다. 따라서 어떤 이유로 이러한 링크 (예 : "/cabel")는 BeautifulSoup에 보이지 않습니다. 나는 이유를 이해하지 못한다.
해결책
나는 BeautifulSoup이 정식 HTML 구문 분석 모듈이라는 것을 알고 있지만 때로는 일부 HTML에서 일부 하위 문자열을 긁어 내고 싶을 때 Pyparsing에는 유용한 방법이 있습니다. 이 코드 사용 :
from pyparsing import makeHTMLTags, withAttribute, SkipTo
import urllib
# get the HTML from your URL
url = "http://www.whitecase.com/Attorneys/List.aspx?LastName=&FirstName="
page = urllib.urlopen(url)
html = page.read()
page.close()
# define opening and closing tag expressions for <td> and <a> tags
# (makeHTMLTags also comprehends tag variations, including attributes,
# upper/lower case, etc.)
tdStart,tdEnd = makeHTMLTags("td")
aStart,aEnd = makeHTMLTags("a")
# only interested in tdStarts if they have "class=altRow" attribute
tdStart.setParseAction(withAttribute(("class","altRow")))
# compose total matching pattern (add trailing tdStart to filter out
# extraneous <td> matches)
patt = tdStart + aStart("a") + SkipTo(aEnd)("text") + aEnd + tdEnd + tdStart
# scan input HTML source for matching refs, and print out the text and
# href values
for ref,s,e in patt.scanString(html):
print ref.text, ref.a.href
Abel에서 Zupikova에 이르기까지 귀하의 페이지에서 914 개의 참조를 추출했습니다.
Abel, Christian /cabel
Acevedo, Linda Jeannine /jacevedo
Acuña, Jennifer /jacuna
Adeyemi, Ike /igbadegesin
Adler, Avraham /aadler
...
Zhu, Jie /jzhu
ZÃdek, AleÅ¡ /azidek
Ziółek, Agnieszka /aziolek
Zitter, Adam /azitter
Zupikova, Jana /jzupikova
다른 팁
한 가지 옵션은 LXML을 사용하는 것입니다 (BeautifulSoup에 익숙하지 않으므로 어떻게 해야하는지 말할 수 없습니다). 기본적으로 지원합니다. xpath
편집하다:
노력하다 (테스트되지 않은) 테스트 :
soup.findAll('td', 'altRow')[1].findAll('a', href=re.compile(r'/.a\w+'), recursive=False)
나는 문서를 사용했다 http://www.crummy.com/software/beautifulsoup/documentation.html
수프는 아름다운 물건이어야합니다
import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html_string)
방금 Zeynel의 이메일에 대한 응답으로 아름다운 수프 메일 링리스트에서 이것에 답했습니다. 기본적으로 웹 페이지에는 구문 분석 중에 아름다운 수프 3.1을 완전히 죽이는 오류가 있지만 아름다운 수프 3.0에 의해 단지 엉망이됩니다.
스레드는에 있습니다 Google 그룹 아카이브.
BeautifulSoup 3.1을 사용하는 것 같습니다
BeautifulSoup 3.0.7로 되돌리는 것이 좋습니다 이 문제)
방금 3.0.7로 테스트했고 기대 결과를 얻었습니다.
>>> soup.findAll(href=re.compile(r'/cabel'))
[<a href="/cabel">Abel, Christian</a>]
BeautifulSoup 3.1로 테스트하면보고있는 결과가 나타납니다. HTML에는 오르포드 된 태그가있을 수 있지만 빠른 모양이 무엇인지 알지 못했습니다.