Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow string results from XPath queries #28

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions tools/scrape
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,13 @@ def main():
parser.add_argument('-r', '--rawinput', action='store_true', default=False,
help="Do not parse HTML before feeding etree (useful"
"for escaping CData)")
parser.add_argument('-x', '--xpath', action='store_true', default=False, help="Force expression to be parsed as XPath")
parser.add_argument('-n', '--nonewline', action='store_true', default=False, help="Do not output trailing newline")
args = parser.parse_args()

args.expression = args.expression.decode('utf-8')

if not args.expression.startswith('//'):
if (not args.expression.startswith('//') and not args.xpath):
from cssselect import GenericTranslator, SelectorError
try:
expression = GenericTranslator().css_to_xpath(args.expression)
Expand All @@ -48,23 +50,31 @@ def main():
else:
document = etree.parse(args.html, html_parser)

if args.nonewline:
trailing = ""
else:
trailing = "\n"

if args.body:
sys.stdout.write("<!DOCTYPE html>\n<html>\n<body>\n")
sys.stdout.write("<!DOCTYPE html>\n<html>\n<body>" + trailing)

for e in document.xpath(expression):
try:
if not args.argument:
text = etree.tostring(e)
if isinstance(e, str):
text = e
else:
text = etree.tostring(e)
else:
text = e.get(args.argument)
if text is not None:
sys.stdout.write(text.encode('utf-8') + "\n")
sys.stdout.write(text.encode('utf-8') + trailing)
sys.stdout.flush()
except IOError:
pass

if args.body:
sys.stdout.write("</body>\n</html>\n")
sys.stdout.write("</body>\n</html>" + trailing)

if __name__ == "__main__":
exit(main())